【问题标题】:React Use Reducer Firing twiceReact 使用 Reducer Firing 两次
【发布时间】:2021-03-24 13:45:48
【问题描述】:

我的问题是当我试图在我的 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 是导致此问题的原因,并且他们说实时模式不会发生此问题,但问题归结为它的开发。

【问题讨论】:

  • 尝试将event.target.checked === true 添加到第一个条件

标签: reactjs react-hooks use-reducer


【解决方案1】:

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

使用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
  });
}

【讨论】:

  • 不客气 :) 我还会更改操作以使其更简单。查看更新的答案。
  • 我喜欢使用输入字段中的选定值。再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2020-08-07
  • 2012-02-18
相关资源
最近更新 更多