[英]remove object from array in react
我有一個狀態保存的對象數組,該數組中的每個對象在對象上都有另一個數組。
這是單個對象的示例:
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]]
})
})
},
看起來您的setState
調用僅使用一個特定scratchTicker
content
的值覆蓋了scratchTickers
數據。
實際上,您要做的是將 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/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
更新:
渲染時,請確保是否使用的迭代器未將數組索引用作鍵,例如這樣。
// bad
{content.map((content, index) =>
<p key={index}>{content.Content}</p>
)}
當React對虛擬DOM進行更改時,它將查看鍵以確定已更改的內容。 因此,如果您使用的是索引,但數組中少了一個,它將刪除最后一個。 而是將content
的id
用作鍵,像這樣。
// good
{content.map(content =>
<p key={content.id}>{content.Content}</p>
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.