我已经构建了一个全局状态 redux,如带有上下文和挂钩的模式。有没有办法组合减速器?

I have built a global state redux like pattern with context and hooks. Is there a way to combine reducers?

我已经构建了一个全局状态提供程序上下文,以及一个带有 useReducer Hook 的缩减器。我意识到像在 redux 中那样组合多个 reducer 是有问题的。有没有好的方法来做到这一点?我见过有人从 redux 本身导入 combineReducers,这似乎有点违背了重点。有人对此有任何见解吗?

不确定这是否是您要查找的内容,但我已经使用类似下面的内容来组合多个减速器。它实际上减少了减速器。实际上不像 redux combineReducers 和 key/value。

const reduceReducers = (...reducers) => (prevState, value, ...args) =>
  reducers.reduce(
    (newState, reducer) => reducer(newState, value, ...args),
    prevState
  );

我会被这样使用:

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

function reducerB(state, action) {
  switch (action.type) {
    case "double":
      return { ...state, count: state.count * 2 };
    case "halve":
      return { ...state, count: state.count / 2 };
    default:
      return state;
  }
}

export default reduceReducers(reducerA, reducerB);

然后组件:

import reducers from "./reducers";

function Counter({ initialState = { count: 1 } }) {
  const [state, dispatch] = useReducer(reducers, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "double" })}>x2</button>
      <button onClick={() => dispatch({ type: "halve" })}>/2</button>
    </>
  );
}