React 使用 Reducer 触发两次

React Use Reducer Firing twice

我的问题是当我试图在我的 useReducer 函数中切换布尔值时,这样做会导致值变回原始值的问题:

function reducerBalls(state: any, action: any) {
    let newState;
    let item;
    switch (action.type) {
      case ACTIONS.INIT:
        return action.balls;
        
      case ACTIONS.SELECTED:
        newState = [...state];
        item = newState[action.index] ;
        item.active = !item.active;
        return newState;

      default:
        return state;
    }}

这里是调度事件

function ballCheckboxHandler(ball: lotteryBalls, event: any) {
        if(event.target.checked) {
            return dispatch({type: ACTIONS.SELECTED, index: ball.number});
        }
        if(event.target.checked === false) {
            return dispatch({type: ACTIONS.UNSELECTED, index: ball.number});
        }
    }

现在我知道 react.StrictMode 是导致此问题的原因,而实时模式他们说这个问题不会发生,但问题归结为它的开发。

您对数组进行浅克隆,但随后改变了实际对象,因此项目本身不会重新呈现。

使用 spread 克隆对象 newState[action.index],并更改 active 属性:

function reducerBalls(state: any, action: any) {
  switch (action.type) {
    case ACTIONS.INIT:
      return action.balls;

    case ACTIONS.SELECTED:
      const newState = [...state];
      newState[action.index] = { 
      
        ...newState[action.index], 
        active: !newState[action.index].active
      };
      
      return newState;

    default:
      return state;
  }
}

我还会更改操作的工作方式以使其更简单一些:

function reducerBalls(state: any, action: any) {
  switch (action.type) {
    case ACTIONS.INIT:
      return action.balls;

    case ACTIONS.SELECTED:
      const newState = [...state];
      newState[action.index] = { 
        ...newState[action.index], 
        active: action.selected // use the selected value
      };
      
      return newState;

    default:
      return state;
  }
}

function ballCheckboxHandler(ball: lotteryBalls, event: any) {
  return dispatch({
    type: ACTIONS.SELECTED,
    index: ball.number,
    selected: event.target.checked // selected is the checked state of the event
  });
}