我知道您應該使用setstate更新React中的狀態。我有一個狀態對象數組,我想更新一個特定的元素。我怎樣才能做到這一點。我的數據和代碼如下:Javascript更新基於子集的對象數組中的特定元素
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);
});
你能發佈你正在使用的實際React代碼嗎?在React中調用'setState'是更正React特定狀態的正確方法是正確的,它聽起來像從代碼中看到的那樣,只是詢問如何更新數組中的項目,而不考慮React – azium
是的,這是正確的,但我想提供我參考的代碼。它更像是一個javascript問題,除了我需要在set狀態下進行更新之外。 –