Remove Object From Array In React
Solution 1:
It looks like your setState
call is overriding your scratchTickers
data with just the value of one particular scratchTicker
's content
.
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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/maphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Update:
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) =><pkey={index}>{content.Content}</p>
)}
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 =><pkey={content.id}>{content.Content}</p>
)}
Post a Comment for "Remove Object From Array In React"