我正在构建一个todo列表,我得到了一个更新,即将数据添加到本地存储,这样如果刷新选项卡,数据就会从本地存储中检索。问题是,当添加第二个任务时,第一个任务会上传到本地存储
functionToSetLocalStorage () {
console.log(this.state.items);
}
addItem(e) {
if (this._inputElement.value !== "") {
var newItem = {
text: this._inputElement.value,
key: Date.now()
}
console.log(this.state.items);
this.setState((prevState) =>{
return {
items: prevState.items.concat(newItem)
}
}, this.functionToSetLocalStorage);
console.log(this.state.items);
this._inputElement.value = "";
}
e.preventDefault();
localStorage.setItem('todoEntries',JSON.stringify(this.state.items));
}
有人能帮我解释一下为什么会延期吗?
setState
是异步函数
在返回新状态之前,请尝试在setState函数中添加localStorage.setItem('todoEntries',JSON.stringify(this.state.items));
。
this.setState((prevState) =>{
localStorage.setItem('todoEntries',JSON.stringify(prevState.items.concat(newItem) ));
return {
items: prevState.items.concat(newItem)
}
}, this.functionToSetLocalStorage);