【问题标题】:Remove an item from a nested array with React Hooks使用 React Hooks 从嵌套数组中删除一个项目
【发布时间】:2021-09-06 23:44:55
【问题描述】:

我正在尝试使用 React Hooks 从我的状态中删除一个项目。我不知道我做错了什么。

我的数据如下所示,我正在尝试删除“items”数组中的单个项目。

const MYDATA = {
    id: '0001',
    title: 'A good title',
    items: [
      {
        itemid: 0,
        title: 'Cheddar',
        variants: [
          { id: '062518', grams: 200, price: 3.00},
          { id: '071928', grams: 400, price: 5.50},
        ]
      },
      {
        itemid: 1,
        title: 'Edam',
        variants: [
          { id: '183038', grams: 220, price: 2.50},
          { id: '194846', grams: 460, price: 4.99},
        ]
      },
      {
        itemid: 2,
        title: 'Red Leicester',
        variants: [
          { id: '293834', grams: 420, price: 4.25},
          { id: '293837', grams: 660, price: 5.99},
        ]
      }
    ]
  }

当我单击“删除”按钮时,地图会中断,我认为这是因为我的状态格式不正确,但我不确定。

我面临的问题的一个例子可以在这里看到 - https://codesandbox.io/s/frosty-joliot-4wp1q?file=/src/App.js

任何帮助将不胜感激。

【问题讨论】:

标签: javascript arrays reactjs react-hooks


【解决方案1】:

您的items 已嵌入其中。


  const removeMyCheese = (cheeseId) => {
    console.log(cheeseId)

    setMyCheeses(prev => {
      const items = prev.items.filter(item => item.itemid !== cheeseId)
      return {
        ...prev,
        items
      }
    })

  }

随意修改它,无论你的逻辑是什么,我现在只删除那个项目。

【讨论】:

  • 如果您认为它解决了您的问题,请接受答案。谢谢。
【解决方案2】:

问题是您在对象而不是数组上执行map。因此,您会得到未定义的错误。也许您打算在myCheeses.items 上运行地图功能?

【讨论】:

    【解决方案3】:

    这个问题是由于你应该在一个数组上应用.map(这里是你的item)。您可以使用:

    const removeMyCheese = (cheeseId) => {
        console.log(cheeseId);
        setMyCheeses((prevState) => {
          let items = prev.items.filter(item=>item.itemid!==cheeseId);
          return {
            ...prevState,
            items
          };
        });
      };
    

    或者(虽然这不是一个好的解决方案 => splice 改变状态,这在 React 中是不好的做法。)

    const removeMyCheese = (cheeseId) => {
        console.log(cheeseId);
        setMyCheeses((prevState) => {
          let items = prev.items.splice(cheeseId);
          return {
            ...prevState,
            items
          };
        });
      };
    

    【讨论】:

    • splice 改变状态,这在 React 中是不好的做法。
    • @EmileBergeron 我不知道,我根据过滤修改了答案并添加了您的评论。谢谢。
    • 更好,但我不能推荐足够的 not 在这个用例中使用 splice
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多