所以说我有一个像这样的数组:
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
我想向第一个对象添加一个数组,使其看起来像这样。
this.state = {
students: [{
"company": "This",
"firstName": "Randy",
"id": "1",
"lastName": "Orton",
"array" : []
},
{
"company": "That",
"firstName": "Clark",
"id": "2",
"lastName": "Kent",
}]
}
我该怎么做而又不弄乱初始状态,而只更新它?
答案 0 :(得分:2)
您可以尝试使用以下方式:
this.state.students[0].array = [];
this.state.students.find(x => x.company === 'This').array = [];
从服务器获取响应后,可以立即向每个array
对象添加student
属性:
示例:
var obj = {};
$.ajax({
type: 'POST',
url: '/yourAPIUrl'
}).done(function (response) {
obj.state = reponse;
for (var student of obj.state.students) {
student.array = [];
}
});