连续成功触发两个 useReducer 钩子

Successfully firing two useReducer hooks in a row

我有一个 useReducer 钩子

const [state, dispatch] = React.useReducer(reducer, initialState);

状态设置字符串有两种情况

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');
  }
}

如果我连续调用 dispatch 两次,那么只有最后一次调用会注册,就像组件设置状态一样。

dispatch({ type: 'ONE', payload: 'some string' });
dispatch({ type: 'TWO', payload: 'some other string' });

如何让两个调度调用都注册,而不仅仅是最后一个?

您正在覆盖状态。

而不是做 return { a: action.payload }; ,使用:

return { ...state, a: action.payload };

另一种情况也是如此