javascript 使用 React.js 一段时间后状态更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31308309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
State change after a certain amount of time with React.js
提问by user1072337
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?
我有一个特定的变量作为状态在 false 和 true 之间切换(我们可以称之为提交)。我想要做的是在几秒钟后将状态设置为 true 后更改回 false。我该怎么做?
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?
我想补充一点,我有一个计时器将提交的变量设置为 false。我该怎么做呢?
回答by baao
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
}
}