简体   繁体   中英

React - this.setState and this.forceUpdate doesn't update state to hold latest values

I have a form which shows data based on a date range. On first time load, > it shows data for last 1 hour. I am using react date > > > > picker to render start and end times. When user changes start and end > > > dates, below function is called. In this function, I am trying to set > > > state with user-selected start and end dates, but state always holds > > > previous start and end date value

  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);
           }

setState does not immediately mutate state - From Reacts documentation:

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

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

This code should be in render for you to see the update.:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM