簡體   English   中英

useState 從數組中刪除項目

[英]useState remove item from array

我正在嘗試從錯誤中刪除一個項目,但它沒有按預期工作。

我使用狀態:

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

我有一個按鈕來添加操作:

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

每行都有一個刪除,我正在嘗試使用行索引刪除操作數組中的項目:

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

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

嘗試使用filter 它不會修改現有數組,可以像這樣使用:

setActions(prevActions => (
  // Filter out the item with the matching index
  prevActions.filter((value, i) => i !== index)
));
  <IconButton
    disabled={actions.length === 1}
    icon="dash"
    iconColor="red"
    onClick={() => {
      setActions(actions.filter((item, i) => i !== index));
    }}
  />

我在你的 Codesandbox 中測試了它並且它有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM