我知道你应该使用 setstate 来更新 React 中的状态。我有一个处于状态的对象数组,我想更新特定元素。我怎样才能做到这一点。我的数据和代码如下:
var trans = [{
"_id" : ObjectId("583f6e6d14c8042dd7c979e6"),
"transid" : 1,
"acct" : "acct1",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category1",
"amount" : 103
},
{
"_id" : ObjectId("583f6e6d14c8042dd7c2132t6"),
"transid" : 2,
"acct" : "acct2",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category2",
"amount" : 103
},
{
"_id" : ObjectId("583f6e6d14c8042dd7c152g2"),
"transid" : 3,
"acct" : "acct3",
"transdate" : ISODate("2012-01-31T05:00:00.000Z"),
"category" : "category3",
"amount" : 103
}]
let transFilter=[];
trans.forEach(function(el){
if(parseInt(el.transid).indexOf(parseInt(1))!=-1)
transFilter.push(el);
});
transFilter.category = "category4";
//this is where I'm not sure how to just update the corresponding record to
//the one in transFilter for tmpTrans; the data in trans is a copy of the data in tmpTrans
this.setState({tmpTrans: transFilter}, function () {
console.log(tmpTrans);
});
最佳答案
map
是一个相当简单的函数,可用于创建修改后的数组。
考虑以下项目数组:
var data = [
{ id: 1, category: 'sports' },
{ id: 2, category: 'movies' }
]
如果您想更改 id 为 2 的项目的类别,您可以映射数组并使用 Object.assign
创建具有新类别的对象副本(如果 id 匹配) :
var newData = data.map(item => {
if (item.id === 2) {
return Object.assign({}, item, { category: 'food' })
}
return item
})
现在,使用新创建的数据,您可以简单地设置状态:
this.setState({ data: newData })
关于Javascript根据子集更新对象数组中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41214926/