如何在React JS中使用动态键设置状态数组

时间:2018-06-22 05:42:24

标签: reactjs

我具有以下状态值作为数组。如何将新列表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",
            }
        ]
    }
}

3 个答案:

答案 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 }
    } }