简体   繁体   English

使用React.js在一定时间后更改状态

[英]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). 我有一个在false和true之间切换的某个变量作为一个状态(我们可以称之为提交)。 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. 我想做的是在几秒钟之后将状态更改设置为true后将状态更改为false。 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. 我想补充一点,我有一个计时器设置变量提交回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 请记住, bind(this)到超时功能,使this指的是正确的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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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