簡體   English   中英

如何修改和擴展位於 useState 數組中的對象的屬性?

[英]How can I modify and extend properties of an object located in useState Array?

我是 react.js 初學者,正在尋找改變我的數據結構的方法。 例如,我想將新對象推入 children-array 或按鍵刪除它們。

這樣做的適當方法是什么?

const [treeData, setTreeData] = useState([
  {
    title: "parent 1",
    key: "0-0",
    icon: <UserAddOutlined />,
    children: [
      {
        title: "parent 1-0",
        key: "0-0-0",
        icon: <UserAddOutlined />,
        children: [
          {
            title: "leaf",
            key: "0-0-0-0",
            icon: <UserAddOutlined />,
          },
          {
            title: "leaf",
            key: "0-0-0-1",
            icon: <UserAddOutlined />,
          },
        ],
      },
      {
        title: "parent 1-1",
        key: "0-0-1",
        icon: <UserAddOutlined />,
        children: [
          {
            title: "sss",
            key: "0-0-1-0",
            icon: <UserAddOutlined />,
          },
        ],
      },
    ],
  },
]);

所以你不應該直接更新狀態。 不允許。

在此處輸入圖像描述

也許您從哪里接收數據,假設通過 api 並且數據是response.payload.data等。

因此,在您的情況下,請使用setTreeData(response.payload.data)方法在其中添加內容。

現在,如果您想更新某些值(使用索引等刪除或更新)。 顯然,您必須以某種方式擁有索引。

所以對於刪除說你會有一些點擊和反對它的處理程序

removeItem(e) {
  item_to_remove = e.target..... etc // to get the item's reference for matching
setTreeData(treeData.filter(items => item.<someproperty> != item_to_remove))
// In your case could also be targetting children maybe
// setTreeData(treeData.Children.filter(items => item.<someproperty> != item_to_remove))
}

我會說也許在另一個 useState 變量(可能是childrenTreeData )中處理兒童數組。 但是你也必須看看它的可行性。 只是看到你的數據后的想法

只是為了信息

這與我為更新項目中每張卡內的價格所做的類似

  const getCurrentPrice = useCallback(() => {    // <======= maybe you do not need this
    const updatedTilesData = tilesData.map((tile: any) => {
      return {
        ...tile,  // <======= get everything here and then update the price below for item
        currentPrice: calculateDNCurrentPrice(
          tile.startingPrice,
          tile.dnTimestamp
        ),
      };
    });
    setTilesData(updatedTilesData);
  }, [tilesData]);

暫無
暫無

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

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