连续成功触发两个useReducer挂钩

时间:2019-02-09 10:06:19

标签: reactjs react-hooks

我有一个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({ type: 'ONE', payload: 'some string' });
dispatch({ type: 'TWO', payload: 'some other string' });

如何获得两个派遣电话进行注册,而不仅仅是最后一个?

1 个答案:

答案 0 :(得分:4)

您正在覆盖状态。

使用{

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

其他情况也一样

相关问题