Jos*_*man 1 reactjs react-hooks
我有一个useReducer挂钩
const [state, dispatch] = React.useReducer(reducer, initialState);
Run Code Online (Sandbox Code Playgroud)
它有两种情况将状态设置为字符串
function reducer(state, action) {
switch (action.type) {
case 'ONE':
return { a: action.payload };
case 'TWO':
return { b: action.payload };
default:
throw new Error('You have probably mispelt the action name');
}
}
Run Code Online (Sandbox Code Playgroud)
如果我连续两次调用dispatch,那么只有最后一个调用寄存器,就像组件设置状态一样。
dispatch({ type: 'ONE', payload: 'some string' });
dispatch({ type: 'TWO', payload: 'some other string' });
Run Code Online (Sandbox Code Playgroud)
如何获得两个调度调用进行注册,而不仅仅是最后一个?
您正在覆盖状态。
代替这样做return { a: action.payload };,使用:
return { ...state, a: action.payload };
Run Code Online (Sandbox Code Playgroud)
其他情况也一样