【问题标题】:remove object from array in react在反应中从数组中删除对象
【发布时间】:2023-03-13 00:53:01
【问题描述】:

我有一个保存在状态中的对象数组,并且数组中的每个对象都有另一个对象数组。

这里是单个对象的示例:

            id       : uuid.v1(),
            area     : 'Scratch',
            name     : 'Untitled',
            status   : "",
            size     : "",
            created  : {
                name : "username",
                time : new Date()
            },
            modified : {
                name : "username",
                time : new Date()
            },
            content: [{
                id        : uuid.v1(),
                Content   : "Content 1",
                TowerRed  : "",
                TowerText : "text"
            },
            {
                id        : uuid.v1(),
                Content   : "Content 2",
                TowerRed  : "",
                TowerText : "text"
            }]

我需要能够从这些对象内部的内容数组中删除一个对象。

例如我需要删除包含“内容 1”的对象而不修改包含“内容 2”的对象

我曾尝试使用她的反应不变性助手,但没有成功。

在这里,我循环遍历父对象和内容对象,直到找到与“itemID”匹配的 (itemID) 是我要从内容数组中删除的对象的 ID。

     var tickerIndex = null;
        var tickerItemIndex = null;

        for (var i = 0; i < this.state.scratchTickers.length; i++) {

            var tickersContent = this.state.scratchTickers[i].content;
            tickerIndex = i;

            for (var x = 0; x < tickersContent.length; x++) {
                if (tickersContent[x].id == itemID) {                   
                    tickerItemIndex = x;
                }           
            }
        }

然后我创建对父对象及其内容数组的引用:

var item = this.state.scratchTickers[tickerIndex].content;

最后我使用更新不变性帮助拼接数组并根据其 itemID 删除正确的对象:

this.setState ({
        scratchTickers: update(item, {
            $splice: [[tickerItemIndex, 1]]
        })
    })

但这似乎不起作用。

这是整个函数:

_deleteTickerItem: function(itemID) {
        var tickerIndex = null;
        var tickerItemIndex = null;

        for (var i = 0; i < this.state.scratchTickers.length; i++) {

            var tickersContent = this.state.scratchTickers[i].content;
            tickerIndex = i;

            for (var x = 0; x < tickersContent.length; x++) {
                if (tickersContent[x].id == itemID) {                   
                    tickerItemIndex = x;
                }           
            }
        }

        var item = this.state.scratchTickers[tickerIndex].content;

        this.setState ({
            scratchTickers: update(item, {
                $splice: [[tickerItemIndex, 1]]
            })
        })

    },

【问题讨论】:

  • 你可以使用 lodash 的 _.reject() 方法 object.content = _.reject(object.content, {Content: 'Content 1'});
  • @Michael 感谢您的建议,我现在可以使用 _.reject() 函数,知道如何将该对象推入状态保持的对象数组中吗? var item = this.state.scratchTickers[tickerIndex].content; item = _.reject(item, {id: itemID});

标签: javascript arrays reactjs


【解决方案1】:

您的setState 调用似乎仅使用一个特定scratchTickercontent 的值覆盖了您的scratchTickers 数据。

您实际上要做的是将您的scratchTickers 数组映射 到具有过滤内容的新数组。

_deleteTickerItem: function(itemID) {
  this.setState({
    scratchTickers: this.state.scratchTickers.map(scratchTicker =>
      Object.assign({}, scratchTicker, {
        content: scratchTicker.content.filter(content => content.id != itemID)
      })
    )
  });
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

更新:

渲染时,请确保您使用的是迭代器,而不是像这样使用数组索引作为键。

// bad
{content.map((content, index) =>
  <p key={index}>{content.Content}</p>
)}

当 React 在更改时与虚拟 DOM 进行比较时,它会查看键以确定更改的内容。因此,如果您使用索引并且数组中少了一个,它将删除最后一个。而是使用contentid 作为键,如下所示。

// good
{content.map(content =>
  <p key={content.id}>{content.Content}</p>
)}

【讨论】:

  • 嗨,感谢您的信息,这在删除项目的事实中起作用,但它似乎只是删除了数组中的最后一个对象而不是指定的对象
  • 嗯,我在这里做了一个 JSBin,似乎可以正常工作。 jsbin.com/qirizuw/edit?js,console
  • 啊,我认为这是我的问题,因为我删除了 state 的设置并且只是 console.logged 结果并且它是完整的删除了正确的对象。
猜你喜欢
  • 2022-09-29
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多