0

我尝试了useReducer 的示例代码

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  // ...

并在 App 中实例化了 3 个计数器。示例:https ://codesandbox.io/s/serene-morse-c017r

所以看起来状态对于每个 Counter 组件都是本地的,而不是像 Redux 上的“单一事实来源”?如果 App 想要获取所有 counter 的值,或者一个 Counter 想要获取另一个 Counter 的值,那该怎么做呢?

4

1 回答 1

1

我对您的代码和框进行了更改,并使用上下文使您的计数器成为像 redux 一样的单一事实来源。

import React from "react";
const CountStateContext = React.createContext();
const CountDispatchContext = React.createContext();
function countReducer(state, action) {
  switch (action.type) {
    case "increment": {
      return { count: state.count + 1 };
    }
    case "decrement": {
      return { count: state.count - 1 };
    }
    default: {
      throw new Error(`Unhandled action type: ${action.type}`);
    }
  }
}
function CountProvider({ children }) {
  const [state, dispatch] = React.useReducer(countReducer, { count: 0 });
  return (
    <CountStateContext.Provider value={state}>
      <CountDispatchContext.Provider value={dispatch}>
        {children}
      </CountDispatchContext.Provider>
    </CountStateContext.Provider>
  );
}
function useCountState() {
  const context = React.useContext(CountStateContext);
  if (context === undefined) {
    throw new Error("useCountState must be used within a CountProvider");
  }
  return context;
}
function useCountDispatch() {
  const context = React.useContext(CountDispatchContext);
  if (context === undefined) {
    throw new Error("useCountDispatch must be used within a CountProvider");
  }
  return context;
}
export { CountProvider, useCountState, useCountDispatch };

https://codesandbox.io/s/modern-wildflower-ihvjj

于 2020-02-14T09:33:40.723 回答