【发布时间】:2016-12-19 02:14:32
【问题描述】:
我了解您应该使用 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);
});
【问题讨论】:
-
你能发布你正在使用的实际 React 代码吗?你是对的,在 React 中调用
setState是更新 React 特定状态的正确方法,从你的代码听起来和看起来你只是在询问如何更新数组中的项目,而不管 React -
是的,没错,但我想提供我引用的代码。这更像是一个 javascript 问题,除了我需要在设置状态下进行更新。
标签: javascript arrays object reactjs