繁体   English   中英

ReactJS:单击按钮时调用计时器功能

[英]ReactJS: Call a timer function on button click

请注意:这不是ReactJS的副本-需要单击两次以设置State和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的新手,所以我目前不知道该怎么做。 非常感谢你。

setState使用回调方法,因为要花费一些时间来改变状态,并且由于JS是异步的, this.startTime()即使在状态发生改变之前this.startTime()执行this.startTime() ,因此您需要第二次单击来执行相同的操作,但是这样做状态已经改变并因此起作用的时间

changeGameStatus = (status) => {
    console.log('status = ' + status)
    this.setState({
        game: {
            status: status
        }
    }, () => {
         console.log('new status:' + this.state.game.status)

    this.startTimer()
    })

}

暂无
暂无

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

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