【发布时间】:2017-04-17 14:23:52
【问题描述】:
请注意:这不是 ReactJS - Need to click twice to set State and run function 的副本。那里的解决方案对我不起作用。
这是我最初的state:
constructor(props) {
super(props)
this.state = {
/* some code */
game: { // game-level
/* some code */
/* value options: 'ready' 'in-progress', 'paused', 'cleared' */
status: 'ready'
},
} /* END state */
} /* END constructor */
我正在尝试在单击按钮时将this.state.game.status 更改为in-progress,一旦更改,我想启动一个计时器。
render()里面的按钮:
<RaisedButton label="Start" primary={true}
onClick={()=> this.changeGameStatus('in-progress')} />
点击按钮时调用的函数:
changeGameStatus = (status) => {
console.log('status = ' + status)
this.setState({
game: {
status: status
}
})
console.log('new status:' + this.state.game.status)
this.startTimer()
}
startTimer() 函数
startTimer() {
if (this.state.game.status === 'in-progress') {
console.log('The timer has started')
this.timerID = setInterval(
() => this.updateTimer(),
1000
)
}
} /* END startTimer */
问题是,this.state.game.status 在第一次单击按钮时不会更新,因此不会启动计时器。我必须点击按钮两次才能使整个工作正常进行,这不是非常可取的。
注意:
我上面提到的另一个问题有一个答案,但它指定我调用componentWillUpdate() 内部的函数。它对我不起作用,因为它每次滴答都会调用startTimer(),从而使计时器每次运行速度都快两倍。
如何通过单击按钮更新我的状态并调用计时器功能?我认为这很简单,但我是 ReactJS 的新手,所以我现在不知道该怎么做。非常感谢。
【问题讨论】:
标签: javascript reactjs timer