Javascript 我的todolist中存在时间延迟,无法将数据快速上载到本地存储

Javascript 我的todolist中存在时间延迟,无法将数据快速上载到本地存储,javascript,reactjs,Javascript,Reactjs,我正在构建一个待办事项列表,我得到了一个更新,即将数据添加到localstorage,以便在刷新选项卡时从localstorage检索数据,问题是当添加第二个任务时,第一个任务会上载到localstorage functionToSetLocalStorage () { console.log(this.state.items); } addItem(e) { if (this._inputElement.value !== "") {

我正在构建一个待办事项列表,我得到了一个更新,即将数据添加到localstorage,以便在刷新选项卡时从localstorage检索数据,问题是当添加第二个任务时,第一个任务会上载到localstorage

  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
是异步函数
尝试添加
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);
           
        

@Mantankumbhar没有删除localStorage.setItem('todoEntries',JSON.stringify(this.state.items));最后呢?是啊too@ManthanKumbhar我的错误是我在答案中修复了JSON.stringify(prevState.items.concat(newItem))