2017-04-17 58 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

如果有幫助,你能接受這個答案嗎? –