2017-02-10 79 views
0

我有一個窗體顯示基於日期範圍的數據。第一次加載時,>它顯示最近1小時的數據。我正在使用react date>>>> picker來呈現開始和結束時間。當用戶更改開始和結束>>>日期時,調用下面的函數。在此功能,我想設置>>>狀態與用戶選擇的開始和結束日期,但狀態一直認爲>>>前面的開始日期和結束日期值React - this.setState和this.forceUpdate不更新狀態以保存最新值

refreshTableOnDateChange(startDateSelected,endDateSelected) { 
      this.setState({startDate: null, endDate: null}); 
      console.log("inside refreshTableOnDateChange this.state.startDate is", startDateSelected); 
      console.log("inside refreshTableOnDateChange this.state.endDate is", endDateSelected); 
      let startDateFormatted = startDateSelected.format('YYYY-MM-DD HH:mm'); 
      let endDateFormatted = endDateSelected.format('YYYY-MM-DD HH:mm'); 
       this.setState({startDate: startDateFormatted, endDate: endDateFormatted}); 
       this.forceUpdate(); 
       console.log("start date is", this.state.startDate); 
      console.log("end date is", this.state.endDate); 
      this.load(this.state.orderType); 
      } 

回答

0

的setState不會立即發生變異狀態 - 從反應文檔:

https://facebook.github.io/react/docs/react-component.html#setstate

的setState()不會立即發生變異this.state而是創建一個 掛起狀態轉變。調用 方法後訪問this.state可能會返回現有值。沒有 保證同步操作對setState的調用,並且調用可能爲 進行批處理以提高性能。

此代碼應該是呈現給你看更新:

 console.log("start date is", this.state.startDate);