从react中的数组中删除对象 [英] remove object from array in react

查看:1188
本文介绍了从react中的数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of objects saved in state and each of the objects in the array has another array on objects.

下面是一个对象的示例:

here is an example of a single object:

            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"
            }]

我需要能够从中删除对象

I need to be able to remove an object from inside the content array inside of these objects.

例如,我需要删除包含 content 1的对象,而不修改包含 content 2的对象。

For example I need to remove the object containing 'content 1' without modifying the object containing 'content 2'

我尝试使用react不变性帮助器,但没有成功。

I have tried to use the react immutability helpers her but with no success.

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

here I loop through the parent objects and the content objects until I find a match with the 'itemID' (itemID) is the id of the object i want to remove form the content array.

     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;
                }           
            }
        }

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

then I create a reference to the parent object and its content array:

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

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

Finally I use the update immuatbility help to splice the array and remove the correct object based on its 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]]
            })
        })

    },


推荐答案

它看起来您的 setState 调用正在使用一个特定的 scratchTicker的值覆盖您的 scratchTickers 数据内容

It looks like your setState call is overriding your scratchTickers data with just the value of one particular scratchTicker's content.

您本质上想做的是将您的 scratchTickers 数组映射到具有过滤内容的新数组。

What you're essentially trying to do is map your array of scratchTickers to a new array with filtered content.

_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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https:/ /developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

更新:

渲染时,请确保您使用的是迭代器

When rendering, make sure if you're using an iterator that you're not using the array indices as keys, like this.

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

React在更改时与虚拟DOM进行差异比较时,它将查看键来确定已更改的内容。因此,如果您使用的是索引,但数组中少了一个,它将删除最后一个。而是使用内容 id 作为键,像这样。

When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.

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

这篇关于从react中的数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆