我有一个没有 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/