簡體   English   中英

如何在 React js 中增加 Object 數組中的 Object?

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

我想在數組科目的數組學生中增加 object。 state 如下所示:

  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 。 請任何人都可以幫我解決上述 state 格式的問題...請不要建議我更改我的 state 數據格式。 我正在使用 React js..

除了打字錯誤,我認為您需要將 map 的結果設置回 state,否則您將多次覆蓋 state。

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

請注意,這將為數組中的每個subjects添加一個新條目,如果您需要它是有條件的,您只需更改 map 以僅對特定學生執行更改,例如:

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", duration: "2" }) 推入主題數組

在map() function中調用setState()不好。 您需要創建新的 state 而不改變先前的並立即分配它

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

現在你在 newStudents 中有想要的學生state並且可以調用setState()

this.setState({students: newStudents})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM