结合不使用Redux的Reducer

问题描述 投票:1回答:1

我有一个没有redux的应用程序,我使用钩子和钩子useReducer +上下文来处理全局状态。我有1个useReducer,它像Redux商店一样。但要做到这一点,我只能发送1个减速器。在那个reducer中我拥有状态的所有逻辑,但我想在其他reducers中分离一些减少的函数。在redux中有combineReducer可以做到这一点。但是使用钩子+上下文,我该怎么做?如何组合多个Reducer以将其发送到useReducer中的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;
    }
}

现在这个工作。但是减速器包含的“案例”与其他“案例”完全不同。例如,用于认证的“案例”,用于添加产品的另一个“案例”,用于消除供应商的另一个“案例”等。

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

如果没有Redux,我必须将所有内容混合在一起,只需减少。所以我需要一个combineReducer来组合许多不同的reducer,或者用Hooks + context来完成所有这些的其他方式

reactjs store react-hooks reducers react-context
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.