如何将动作分派给特定的减速器? [英] How to dispatch an action to a specific reducer?
问题描述
我有多个减速器,每个减速器都有一个INIT"类型.我想要实现的是只有相关的reducer可以接收到动作,从动作被触发的位置来判断.有没有中间件可以做到这一点?
您是否在创建减速器时重复使用减速器逻辑?
你可以试试这样的:-
function createCounterWithNamedType(counterName = '') {返回函数计数器(状态 = 0,动作){开关(动作.类型){案例`INCREMENT_${counterName}`:返回状态 + 1;案例`DECREMENT_${counterName}`:返回状态 - 1;默认:返回状态;}}}const rootReducer = combineReducers({counterA : createCounterWithNamedType('A'),counterB : createCounterWithNamedType('B'),counterC : createCounterWithNamedType('C'),});store.dispatch({type : 'INCREMENT_B'});console.log(store.getState());
这就是所谓的高阶 Reducer,您可以通过创建一个包装函数来使用相同的 reducer 逻辑,如上面的代码所示.
您可以在此处查看更多关于高阶Reducers的信息>
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?
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
这篇关于如何将动作分派给特定的减速器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!