Home>

I have been suffering from the problem that the state is not updated until reloading even if setState is done by react for more than a week.

I want to update the information of this.state.name over time, but this.state.name that is displayed does not change even after the set time elapses, and when I refresh the browser, this.state.name "changes" Will be.

Why is the status not updated?
Below is the code for codes andbox.
Try setting this.state.end a few seconds after the current time.

https://codesandbox.io/s/infallible-pond-y8uge?fontsize=14&hidenavigation=1&theme=dark

Corresponding source code
import React from "react";
import dateToFormatString from'./Datefmt';

export default class Human extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            name: "Before changing",
            end: "2020-11-25T23: 01: 00",
        };
    }
    render () {
        const date = dateToFormatString (new Date (),'% YYYY%-% MM%-% DD% T% HH%:% mm%:% ss%');
        if (this.state.name! == "Weird") {
            if (this.state.end<date) {
                this.setState ({name: "Weird"});
            }
        }
        return (
          <>
                 {this.state.name} 
                {date}
          </>
        )
    }
}
  • Answer # 1

    render ()If you write roughlyprops,stateWill be called again when is changed.

    But for time comparisondateIsrender ()It is generated by the processing in
    nextrender ()It does not change unless the conditions for executing are met.

    In the case where it is completed within this class, it can be realized by the following implementation.

    An example of using the entire explanation of this site

    import React from "react";
    import dateToFormatString from "./Datefmt";
    import Clock from "./Clock";
    export default class App extends React.Component {
      constructor (props) {
        super (props);
        this.state = {
          name: "Before changing",
    + date: new Date (),
          end: "2020-11-25T23: 55:00"
        };
      }
    + componentDidMount () {
    + this.intervalId = setInterval (() =>{
    + this.setState ({
    + date: new Date ()
    +});
    +}, 1000);
    +}
    + componentWillUnmount () {
    + clearInterval (this.intervalId);
    +}
      render () {
    --const date = dateToFormatString (new Date (),'% YYYY%-% MM%-% DD% T% HH%:% mm%:% ss%');
    + const date = dateToFormatString (this.state.date, "% YYYY%-% MM%-% DD% T% HH%:% mm%:% ss%");
        if (this.state.name! == "Weird") {
          if (this.state.end<date) {
            this.setState ({name: "strange"});
          }
        }
        return (
        <>
          <Clock />
             {this.state.name} 
            {date}
        </>
        );
      }
    }