I have multiple reducers, each has a type 'INIT'. What I want to achieve is only the relevant reducer can receive the action, judging from where the action was triggered. Is there any middleware can do the trick?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Are you re-using reducer logic while creating reducers?
You can try something like of this :-
function createCounterWithNamedType(counterName = '') {
return function counter(state = 0, action) {
switch (action.type) {
case `INCREMENT_${counterName}`:
return state + 1;
case `DECREMENT_${counterName}`:
return state - 1;
default:
return state;
}
}
}
const rootReducer = combineReducers({
counterA : createCounterWithNamedType('A'),
counterB : createCounterWithNamedType('B'),
counterC : createCounterWithNamedType('C'),
});
store.dispatch({type : 'INCREMENT_B'});
console.log(store.getState());
This is something called Higher Order Reducers in which you can use same reducer logic by creating a wrapper function as shown above in the code above.
You can check more about Higher Order Reducers here
回答2:
I don't think so you can do it that way.
Usually I would have unique type for each reducers and if I need to use the same action for more than one reducers, I will use the combine Reducer functionality to achieve the same.
标签:
react-redux