如何在数组中增加对象,在React js中增加对象的数组



我想增加数组中对象数组主题的学生。状态如下所示:

state = {
students: [{
name: "",
address: "",
class: "",
subjects: [{ subjectName: "", duration: "" }],
},
],
};

我把受试者的句柄增量写如下:

handleIncrement() {
this.state.students.map((student) => {
this.setState({
student: [...student.subjects, { subjectName: "", duration: "" }],
});
});
console.log(this.state);
}

点击按钮增加如下:

<button
type="button"
className="btn btn-primary"
style={myStyle.btnCircle}
onClick={this.handleIncrement}>
<i className="fa fa-plus"></i>
</button>

问题是我不能增加主题数组中的Object。请有人能帮我解决以上州格式的问题吗。。。请不要建议我更改我的状态,数据格式。我正在使用React js。。

抛开打字不谈,我认为您需要将映射的结果设置回state,否则您将多次覆盖state。

handleIncrement() {
this.setState({
students: this.state.students.map((student) => ({
...student,
subjects: [...student.subjects, { subjectName: "", duration: "" }]
}))
});
console.log(this.state);
}

注意,这将为数组中的每个学生向subjects添加一个新条目,如果你需要它是有条件的,你只需要更改映射,只为特定的学生执行更改,例如:

handleIncrement() {
this.setState({
students: this.state.students.map((student) => {
if (student.name !== <name to update>) {
return student;
}
return {
...student,
subjects: [...student.subjects, { subjectName: "", duration: "" }]
};
})
});
console.log(this.state);
}
handleIncrement() {
const newSubject = { subjectName: "", duration: "" }
const newStudents = this.state.students.map((student) => 
{ ... student, subjects: student.subjects.concat(newSubject) })
this.setState({ students: newStudents })
}

我想你所说的增量是指你想把对象(例如{subjectName:"2&",持续时间:"2&;}(推到subject数组中

在map((函数中调用setState((是不好的。你需要在不改变先前状态的情况下创建新状态,并立即分配

let newStudents = state.students.slice(0)
newStudents = newStudents.map(student => {
student.subjects = [...student.subjects, { subjectName: "2", duration: "2" }]
return student
})

现在您在newStudents中有了所需的学生状态,可以调用setState((

this.setState({students: newStudents})

最新更新