简体   繁体   中英

How to Increment the Object inside the Array, Of Array of Object in React js?

I want to increment the object inside the array students of array subjects. And the state is as given below:

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

I write the Handle increment for subjects as below:

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

Button On Click to Increment as below:

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

Problem is I cannot increment the Object inside the subjects array. Please Can anyone help me to solve my problem on the above state format...Please do not suggest me to change my state, Data format. I'm using React js..

Typo aside, I think you need to set the result of your map back to state, or you're going to be overwriting the state multiple times.

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

Note this will add a new entry to subjects for every student in the array, if you need it to be conditional you just need to change the map to only perform the change for the specific student, eg:

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 })
}

I guess what you mean by increment is you want to push object(eg { subjectName: "2", duration: "2" }) into subjects array

It is not good to call setState() in map() function. You need to create new state without mutating previous and assign it at once

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

Now you have desired students state in newStudents and can call setState()

this.setState({students: newStudents})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM