[英]setState an array and object
在將 id 和數據傳遞給 function 后,如何同時設置狀態 object 和數組? 因為評論不是數組的一部分,所以我很困惑。
this.state = {
tasks: [
{ firstName: "boris", lastName: "Johnson", id: uuid() },
{ firstName: "Mary", lastName: "Whithaker", id: uuid() }
],
comment: "This is a comment message"
};
updateTask(id, task, comment, additional) {
const updatedProject = this.state.tasks.map(t => {
if (t.id === id) {
return {
...t,
firstName: task,
lastName: comment
};
}
return t;
});
this.setState({ tasks: updatedProject, comment: additional });
}
您的 State 是 object。 在那個 object 中有兩個字段,任務和評論。 Tasks 是一個對象數組,這些對象具有 firstname、lastname 和 id 字段。 評論是一個字符串。
當該代碼在最后執行setState
時,它正在創建一個新的 object (請參閱{}
),然后將updatedProject
數組用於tasks
,然后將additional
字符串用於comment
。
然后設置整個 object。 數組和字符串是 object 中字段的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.