2017-04-17 184 views
0

请注意:这不是的副本ReactJS - Need to click twice to set State and run function。那里的解决方案不适合我。ReactJS:在点击按钮时调用定时器功能

这是我最初的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.statusin-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的新手,所以我现在不知道该怎么做。非常感谢你。

回答

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() 
    }) 

} 
+0

所以这就是它所谓的......一个'回调'。我已经多次遇到这个语法,但之前无法理解它。非常感谢你!这解决了我的问题。 – ITWitch

+0

是它称为回调函数,只要您在更新的状态下执行异步操作,您就会需要它。 –

+0

如果有帮助,你能接受这个答案吗? –