我有一个没有 redux 的应用程序,我使用钩子和钩子 useReducer + context 处理全局状态。我有 1 个 useReducer,它就像一个 Redux 商店。但要做到这一点我只能发送 1 个减速器。在该减速器中,我拥有所有状态逻辑,但我想将该减速器的一些功能分离到其他减速器中。在redux中,有combineReducer来做到这一点。但是有了钩子+上下文,我该怎么做呢?如何组合多个减速器以将其发送到 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,我可以创建更多的减速器(auth、shopCart、供应商等),并使用 mergeReducer 来控制所有这些。
如果没有 Redux,我必须将所有内容混合在 1 中,然后再减少。所以我需要一个combineReducer来组合许多不同的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>
);
};
减速器.js
const initialState = {};
export default (state = initialState, action) => {
switch (action.type) {
case "action":
return {
...state
};
default:
return state;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)