【问题标题】:Combine Reducer without Redux在没有 Redux 的情况下组合 Reducer
【发布时间】:2019-09-01 08:59:31
【问题描述】:

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

//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 包含的“case”与其他“case”做的事情完全不同。例如认证的“案例”,添加产品的“案例”,消除供应商的“案例”等。

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

如果没有 Redux,我必须将所有内容都混合在 1 中,只需减少即可。所以我需要一个 combineReducer 来组合许多不同的减速器,或者用 Hooks + context 来做这一切的其他方式

【问题讨论】:

    标签: reactjs store react-hooks reducers react-context


    【解决方案1】:

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

    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;
      }
    };
    
    

    【讨论】:

    • 我就是这样开始的。使用多个reducer,useReducer,dispatch。但是这样做的问题是当有许多状态和调度通过提供者作为值发送时。 在某些时候可能有很多值,看起来不太好
    • 在我看来,将您的状态添加到提供程序中的状态键中与export default combineReducers({ reducer1, reducer2 }) 相同。而且我设置它的方式效果很好,因为您的状态与调度分开,因此您只需要关注其中一个即可。向提供者发送多个值有什么问题?您将拥有与 redux 相同的访问权限,不是吗?
    猜你喜欢
    • 2017-09-03
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2022-12-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多