【问题标题】:State not updating on removing value from array in React JSX funcntional component从 React JSX 功能组件中的数组中删除值时状态未更新
【发布时间】:2022-01-02 14:13:00
【问题描述】:

值通过复选框选择添加到数组中,这工作正常并更新状态,但是当我从数组状态中删除值时没有更新但数组正在修改

数组

  const [selectedKeys, setSelectedKeys] = React.useState([]);

事件

 if (event.target.checked) {
               //adding values to array
      setSelectedKeys([...selectedKeys, event.target.value]);
    } else {
      var index = selectedKeys.indexOf(event.target.value);
      if (index >= -1) {
             //Removing values from array
        selectedKeys.splice(index, 1);
      }
      setSelectedKeys(selectedKeys);
    }

【问题讨论】:

  • 你确定代码进入了拼接数组的 if 吗?
  • 是的,我通过放置控制台日志进行了检查

标签: arrays reactjs jsx rendering


【解决方案1】:

splice 方法只是改变现有的数组实例,React 避免重新渲染数组,认为它是同一个数组(React 使用引用相等)。您需要在删除项目后创建一个新数组。

以下任何一种方法都可以

使用扩展运算符创建一个新数组。

if (event.target.checked) {
    //adding values to array
    setSelectedKeys([...selectedKeys, event.target.value]);
} else {
    var index = selectedKeys.indexOf(event.target.value);
    if (index >= -1) {
        //Removing values from array
        selectedKeys.splice(index, 1);
    }
    setSelectedKeys([...selectedKeys]);
}

过滤同样输出新数组的数组

if (event.target.checked) {
    //adding values to array
    setSelectedKeys([...selectedKeys, event.target.value]);
} else {
    var index = selectedKeys.indexOf(event.target.value);
    if (index >= -1) {
        //Removing values from array and set the new array
        setSelectedKeys(
            selectedKeys.filter((item, itemIndex) => itemIndex !== index)
        );
    }
}

【讨论】:

  • @Codecracker,如果它有助于解决您的问题,您能否将其标记为答案?
猜你喜欢
  • 2020-10-14
  • 2020-07-28
  • 2020-08-12
  • 2021-03-11
  • 1970-01-01
  • 2021-03-23
  • 2021-12-24
  • 1970-01-01
  • 2021-10-07
相关资源
最近更新 更多