简体   繁体   中英

ReactJs not updating state

I am a little confused as to why this function of mine will not update the state like it should. I get a date object, then convert it to the format I would like it in, but when I try and set the state at the very bottom, the callback alert is just blank.

How can I make it so the state updates as soon as this function is over?

floorLastCleanedChange(date) {
    this.setState({ flooringLastCleanedTest: date });
    var floorDate = new Date(date);
    alert(floorDate);
    var day = floorDate.getDate();
    if(day.toString().length === 1)
    {
        day = '0' + day;
    }
    var month = floorDate.getMonth() + 1;
    if(month.toString().length === 1)
    {
        month = '0' + month;
    }
    var year = floorDate.getFullYear();
    alert(month+"/"+day+"/"+year);
    this.setState({flooringLastCleaned: month+"/"+day+"/"+year}, alert(this.state.flooringLastCleaned));
}

Try this. The callback to setState is only a function , you were making a function call instead in your code in the callback.

setState(
  {flooringLastCleaned: month+"/"+day+"/"+year},
  () => alert(this.state.flooringLastCleaned);
);

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