Combine Reducer without Redux

浪尽此生 提交于 2020-01-03 17:09:18

问题


I have an application without redux, I handle the global state with hooks and the hook useReducer + context. I have 1 useReducer which makes like a Redux store. But to do this I can only send 1 reducer. In that reducer I have all the logic of the states, but I want to separate some functions of that reduce in other reducers. In redux there is the combineReducer to do this. But with hooks + context, how can I do this? How do I combine many reducers to send it to my Global Provider in the 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;
    }
}

for now this works. But the reducer contains "cases" that do completely different things than other "cases". For example a "case" for authentication, another "case" to add products, another "case" to eliminate suppliers, etc.

With Redux I would have created more reducers (auth, shopCart, suppliers, etc) and use the combineReducer to control all that.

Without Redux I have to have everything mixed in 1 just reduce. So that I need, a combineReducer to combine many different reducers, or some other way of doing all this with Hooks + context


回答1:


I have been developing a bit of a boilerplate with this use case. this is how I am currently doing it.

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



来源:https://stackoverflow.com/questions/55620385/combine-reducer-without-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!