Nic*_*les 7 store reducers reactjs react-context react-hooks
我有一个没有 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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在这有效。但是 reducer 包含的“案例”与其他“案例”做的事情完全不同。例如一个“案例”用于认证,另一个“案例”添加产品,另一个“案例”消除供应商等。
使用 Redux,我会创建更多的 reducer(auth、shopCart、供应商等)并使用 combineReducer 来控制所有这些。
如果没有 Redux,我必须将所有东西都混合在 1 中,只是减少。所以我需要一个 combineReducer 来组合许多不同的减速器,或者其他一些使用 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>
);
};
Run Code Online (Sandbox Code Playgroud)
减速器.js
const initialState = {};
export default (state = initialState, action) => {
switch (action.type) {
case "action":
return {
...state
};
default:
return state;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2867 次 |
| 最近记录: |