我知道您应该使用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);
});
答案 0 :(得分:1)
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 })