Redux框架使用reducer来更改应用程序状态以响应操作。
关键要求是reducer 不能修改现有的状态对象;它必须产生一个新对象。
不好的例子:
import {
ACTIVATE_LOCATION
} from './actions';
export let ui = (state = [], action) => {
switch (action.type) {
case ACTIVATE_LOCATION:
state.activeLocationId = action.id;
break;
}
return state;
};
好例子:
import {
ACTIVATE_LOCATION
} from './actions';
export let ui = (state = [], action) => {
switch (action.type) {
case ACTIVATE_LOCATION:
state = Object.assign({}, state, {
activeLocationId: action.id
});
break;
}
return state;
};
这是Immutable.js的一个很好的用例。