简体   繁体   中英

State change after a certain amount of time with React.js

I have a certain variable that is being toggled between false and true as a state (we can call it submitted). What I would like to do is have the state change back to false after it has been set to true, after a few seconds. How would I do this?

I have this function that is called when a button is clicked, and where the state changes:

saveAndContinue: function(e) {
    e.preventDefault()

    if(this.state.submitted==false) {
        email = this.refs.email.getDOMNode().value
        this.setState({email: email})
        this.setState({submitted: !this.state.submitted});

    }

  }

I would like to add to this, where I have a timer set the variable submitted back to false. How do I do this?

You can set a timeout to reset the state after a given amount of time. Remember to bind(this) to the timeout function so that this refers to the right this

saveAndContinue: function(e) {
    e.preventDefault()

    if(this.state.submitted==false) {
        email = this.refs.email.getDOMNode().value
        this.setState({email: email})
        this.setState({submitted: !this.state.submitted});
        setTimeout(function(){
             this.setState({submitted:false});
        }.bind(this),5000);  // wait 5 seconds, then reset to false
   }
}

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