useState 从数组中删除项目

Bat*_*man 2 javascript arrays reactjs

我正在尝试从错误中删除一个项目,但它没有按预期工作。

我使用状态:

  const [actions, setActions] = useState([
    {
      action: "",
      key: ""
    }
  ]);
Run Code Online (Sandbox Code Playgroud)

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

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

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

      <IconButton
        disabled={actions.length === 1}
        icon="dash"
        iconColor="red"
        onClick={() => {
          console.log(index);
          setActions(actions => {
            return [...actions.splice(index, 1)];
          });
        }}
      />
Run Code Online (Sandbox Code Playgroud)

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

Bri*_*son 9

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

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