Redux 中的 Action 应该是唯一的吗? [英] Should Actions in Redux always be unique?
问题描述
在此示例中,我使用名为 ADD_TODO
In this example I'm using an action named ADD_TODO
import { createStore, combineReducers } from 'redux';
function todos(state, action) {
state = state || [];
switch (action.type) {
case 'ADD_TODO':
return state.concat([ action.text ]);
default:
return state;
}
}
function counter(state, action){
state = state || 0;
switch (action.type){
case 'INCREMENT':
return state+1;
case 'DECREMENT':
return state-1;
case 'ADD_TODO':
return state+100;
default:
return state;
}
}
var app = combineReducers({
todos: todos,
counter: counter
});
var store = createStore(app);
store.dispatch({ type: 'ADD_TODO': text: 'buy eggs' });
这会导致 "todos" 和 "counter" 减速器触发.除非我真的打算这样做,否则我应该让所有减速器都具有独特的作用吗?
This cause both the "todos" and "counter" reducers to trigger. Should I make all reducers have unique actions unless I actually intended it?
我们如何用多个几乎做同样事情的减速器来实现这一点?例如,多个计数器可以有INCREMENT"和DECREMENT"动作.
How can we implement this with multiple reducers that almost do the same thing? Multiple counters for example can have "INCREMENT" and a "DECREMENT" actions.
名称间距操作应该解决它吗?
Should name spacing actions solve it?
例如:POINT_INCREMENT"、POINT_DECREMENT".
eg: "POINT_INCREMENT", "POINT_DECREMENT".
推荐答案
让不同的 reducer 响应同一个动作并没有本质上的错误——例如,如果你一次刷新整个状态.但是,是的,如果您有两个对应于不同事物的计数器,您可能想提出一个命名方案来区分.但我认为动作名称可能应该有一些名词来表明它们适用于什么.
There's nothing inherently wrong with having different reducers respond to the same action -- for example, if you refresh the entire state at once. But yeah, if you have two counters that correspond to different things, you probably want to come up with a naming scheme to differentiate. But I would think the action names probably should have some noun to indicate what they apply to.
这篇关于Redux 中的 Action 应该是唯一的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!