reactjs - 没有 Redux 的情况下组合Reducer

标签 reactjs store react-hooks reducers react-context

我有一个没有 redux 的应用程序,我使用钩子(Hook)和钩子(Hook) useReducer + context 处理全局状态。我有 1 个 useReducer,它就像一个 Redux 商店。但要做到这一点我只能发送 1 个 reducer 。在该 reducer 中,我拥有所有状态逻辑,但我想将该 reducer 的一些功能分离到其他 reducer 中。在redux中,有combineReducer来做到这一点。但是有了钩子(Hook)+上下文,我该怎么做呢?如何组合多个 reducer 以将其发送到 useReducer 中的全局提供商?

//Global Provider
const [state, dispatch] = useReducer(reducer, {
        isAuthenticated: null,
        user: {},
        catSelect: 10,
        productsCart,
        total
 });

//reducer with all cases
export default function(state , action ){

    switch(action.type) {
        case SET_CURRENT_USER:
           return etc...
        case SET_CATEGORIA:
           return etc...
        case 'addCart':
            return etc...
        case etc....
        default: 
            return state;
    }
}

目前这是可行的。但是reducer包含的“cases”做的事情与其他“cases”完全不同。例如一个用于认证的“案例”,另一个用于添加产品的“案例”,另一个用于消除供应商的“案例”等。

使用 Redux,我可以创建更多的 reducer (auth、shopCart、供应商等),并使用 mergeReducer 来控制所有这些。

如果没有 Redux,我必须将所有内容混合在 1 中,然后再减少。所以我需要一个 mixReducer 来组合许多不同的 reducer ,或者使用 Hooks + context 来完成所有这一切的其他方式

最佳答案

我一直在用这个用例开发一些样板。这就是我目前正在做的事情。

Provider.js

import appReducer from "./reducers/app";
import OtherAppReducer from "./reducers/otherApp";

export const AppContext = createContext({});

const Provider = props => {
  const [appState, appDispatch] = useReducer(appReducer, {
    Thing: []
  });

const [otherAppState, otherAppDispatch] = useReducer(OtherAppReducer, {
    anotherThing: []
  });

  return (
    <AppContext.Provider
      value={{
        state: {
          ...appState,
          ...otherAppState
        },
        dispatch: { appDispatch, otherAppDispatch }
      }}
    >
      {props.children}
    </AppContext.Provider>
  );
};

Reducer.js

const initialState = {};

export default (state = initialState, action) => {
  switch (action.type) {
    case "action":
      return {
        ...state
      };
    default:
      return state;
  }
};

关于reactjs - 没有 Redux 的情况下组合Reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55620385/

相关文章:

hadoop - 使用Pig存储在Hbase中时出错

javascript - react Hook : Not getting the state update when using useEffect

javascript - 如何在 React 中使用 useState Hook 更改/添加数组某行的值

javascript - 基于状态响应条件渲染

reactjs - mapbox 图层的正确类型( typescript )在哪里?

PHP MySQL 最接近邮政编码

reactjs - 为什么 useContext 在没有 Context.Provider 的情况下也能工作?

ReactJS 在每次访问页面时仅用一次 window.location.reload() 来启动 useEffect

javascript - 如何将现有项目与jsconfig集成

java - 第二条记录未存储在数组列表中