结合不使用 Redux 的 Reducer [英] Combine Reducer without Redux
问题描述
我有一个没有 redux 的应用程序,我使用钩子和钩子 useReducer + 上下文处理全局状态.我有 1 个 useReducer,它就像一个 Redux 商店.但要做到这一点,我只能发送 1 个减速器.在那个减速器中,我拥有状态的所有逻辑,但我想在其他减速器中分离该减速器的一些功能.在 redux 中有 combineReducer 来做到这一点.但是使用钩子+上下文,我该怎么做?如何在 useReducer 中组合多个 reducer 将其发送到我的 Global Provider?
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;
}
}
现在这有效.但是 reducer 包含的案例"与其他案例"做的事情完全不同.例如一个案例"进行认证,另一个案例"添加产品,另一个案例"消除供应商等.
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.
使用 Redux,我会创建更多的 reducer(auth、shopCart、供应商等)并使用 combineReducer 来控制所有这些.
With Redux I would have created more reducers (auth, shopCart, suppliers, etc) and use the combineReducer to control all that.
如果没有 Redux,我必须将所有东西都混合在 1 中,只是减少.所以我需要一个 combineReducer 来组合许多不同的减速器,或者其他一些使用 Hooks + context 来完成这一切的方式
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
推荐答案
我一直在为此用例开发一些样板.这就是我目前的做法.
I have been developing a bit of a boilerplate with this use case. this is how I am currently doing it.
Provider.js
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;
}
};
这篇关于结合不使用 Redux 的 Reducer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!