[英]react state array not updating
我正在嘗試使用新的以下數組更新我的狀態,但是即使控制台沒有顯示錯誤並正確打印出應該形成的新數組,狀態也不會更新以反映這一點。
我究竟做錯了什么?
state = {
notes: [
{
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
};
updateNotes = (title, name, eventTime) => {
let newNote = {
text: title,
author: name,
time: eventTime
};
this.setState(state => {
const list = state.notes.concat(newNote);
console.log(list); //shows the list formed correctly in the console
return {
list
};
});
};
此處也供參考的是我在運行代碼后在控制台中看到的內容,假設我在創建新筆記時輸入了值、新文本、一些作者和下午 3 點
(3) [{…}, {…}, {…}]
0: {text: "mow the lawn", author: "dean", time: "10am"}
1: {text: "feed the dog", author: "sam", time: "2pm"}
2: {text: "new text", author: "some author", time: "3pm"}
它應該是:
return {
notes: list
};
您現在正在做的是向狀態添加一個新的變量list
。
為什么要更新名為list
的字段,即使您的筆記位於名為notes
字段內?
{ list }
是創建一個對象的簡寫,該對象具有名為list 的字段和存儲在以相同方式命名的變量中的值。
只需更新正確的字段:
return {
notes: list,
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.