我具有以下状态值作为数组。如何将新列表var newList
推入Students
数组中,在该数组中动态生成键Students
,有时可能会将其推入Teachers
数组中。
当前列表位于
let key = "Students"
console.log(this.state.school[key])
我的状态正在变化,我需要根据key
推动新的学生或教师队伍。
this.state = {
school: {
Teachers: [
{
id: "1",
name: "T1",
},
{
id: "2",
name: "T2",
}
],
Students: [
{
id: "1",
name: "S1",
},
{
id: "2",
name: "S2",
}
]
}
}
答案 0 :(得分:1)
您必须以不变的方式更新状态,
let oldArray = this.state.school[key];
this.setState({
school: {
[key]: [
...oldArray,
...newList
]
}
})
通过这种方式,您可以根据 key 值将newList
推送给学生或老师。
答案 1 :(得分:0)
状态是不可变的。您可以使用不变性帮助程序来简化操作。但是在普通的JavaScript中,代码如下:
let { school } = this.state;
school = Object.assign({}, school);
school.students = school.students.concat(newStudents);
this.setState({ school });
使用immutability helper,代码会少一些。
let { school } = this.state;
school = update(school, {
students: {
$push: newStudents
}
);
this.setState({ school });
答案 2 :(得分:0)
查看不变性帮助器。 https://github.com/kolodny/immutability-helper/
import update from ‘immutability-helper’;
...
const newState = update( this.state, {
school: {
[key]: { $push: newList }
} }