useState从数组中删除项目

时间:2020-03-19 20:26:25

标签: javascript arrays reactjs

我正在尝试从错误中删除某项,但是它无法正常工作。

我正在使用状态:

6

我有一个添加操作的按钮:

  const [actions, setActions] = useState([
    {
      action: "",
      key: ""
    }
  ]);

每行都有一个删除,我正在尝试使用行索引删除操作数组中的项目:

    <IconButton
      icon="add"
      bgColor="white"
      iconColor="darkGray"
      onClick={() =>
        setActions([
          ...actions,
          {
            action: "",
            key: ""
          }
        ])
      }
    />

https://codesandbox.io/s/actions-selector-n9xb4

2 个答案:

答案 0 :(得分:4)

尝试使用filter。它不会修改现有的数组,可以这样使用:

setActions(prevActions => (
  // Filter out the item with the matching index
  prevActions.filter((value, i) => i !== index)
));

答案 1 :(得分:0)

currentAuthenticationUser = authenticationUser;

我在您的Codesandbox中对其进行了测试,并且效果很好