由于我的团队使用预先存在的代码作为新更改的模板,因此我尝试在我的应用程序中对 reducer 进行更防御性的编码。出于这个原因,我试图涵盖与不变性的所有潜在偏差。
假设您有一个如下所示的初始状态:
const initialState = {
section1: { a: 1, b: 2, c: 3 },
section2: 'Some string',
};
Run Code Online (Sandbox Code Playgroud)
一个减速器处理这样的动作:
export default function(state = initialState, action) {
switch(action.type) {
case SOME_ACTION:
return { ...state, section1: action.payload.abc };
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以有一个执行以下操作的调度程序:
function foo(dispatch) {
const abc = { a: 0, b: 0, c: 0 };
dispatch({ type: SOME_ACTION, payload: { abc } });
// The following changes the state without dispatching a new action
// and does …Run Code Online (Sandbox Code Playgroud)