【问题标题】:ReactJS: Call a timer function on button clickReactJS:在按钮单击时调用计时器函数
【发布时间】: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


    【解决方案1】:

    setState使用回调方法,因为它需要一些时间来改变状态并且因为JS是异步的,所以this.startTime()甚至在状态改变之前就被执行了,因此你需要第二次点击来做同样的事情但是此时状态已经改变,因此它可以工作

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

    【讨论】:

    • 所以这就是所谓的...callback。我已经多次遇到过该语法,但以前无法理解。非常感谢!这解决了我的问题。
    • 是的,它称为回调,当您对更新状态执行异步操作时,您将需要它。
    • 是的,我已经这样做了。我不得不等待15分钟结束。多么奇怪的过程,你不觉得吗?直到现在我才知道它存在:meta.stackoverflow.com/questions/250132/…
    • 也许他们这样做是因为有时会在这段时间内得到更好的答案
    猜你喜欢
    • 2018-12-11
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多