2016-11-23 68 views
0

試圖遵循一個簡單的時鐘/倒計時教程陣營:爲什麼我的狀態不確定?

constructor(props) { 
    super(props); 
    this.state = { 
     secondsRemaining: 10 
    }; 
    } 

    componentDidMount(){ 
    let interval = setInterval(this.timer, 1000); 
    this.setState({ secondsRemaining: this.state.secondsRemaining }) 
    this.setState({ interval: interval }); 
    }; 

    componentWillUnmount() { 
    clearInterval(this.state.interval); 
    }; 

    timer(){ 
    this.setState({ secondsRemaining: this.state.secondsRemaining -1 }); 
    }; 

很明顯什麼都沒有,但是當我運行它,我得到一個錯誤的定時器功能說cannot read property secondsRemaining of undefined

這可能是什麼愚蠢的我已經錯過了,但我看不出它

跟着這個問題的答案:setInterval in a React app

+0

'this.timer.bind(this)' –

回答

0

myfunction.bind()方法指定在被調用時方法內部將引用this。爲了確保當你調用this.timer()時,你實際上引用了你的組件狀態,而不是引用它的對象,你將不得不通過this.timer.bind(this)

+0

不錯的一個。我會接受它,當我可以:) –

0

由於setInterval將調用this.timer,這將是窗口對象。 您可以使用封:在執行方法的時刻

componentDidMount(){ 
    let currentInstance = this; 
    let interval = setInterval(function(){ currentInstance.timer(); }, 1000); 
    ... 
}; 

componentDidMount它初始化屬性狀態下,保存到變量currentInstance。 然後我們將currentInstance的值關閉到setInterval的第一個參數中。

0

timer定義爲Arrow Function

timer() => this.setState({ secondsRemaining: this.state.secondsRemaining -1 }) 

OR

.bind你的方法裏面constructor

constructor(props) { 
    super(props); 
    this.state = { 
     secondsRemaining: 10 
    }; 
    this.timer = this.timer.bind(this); 
} 

我不建議this.timer.bind(this)render;因爲這樣做,.bind將在每個渲染上創建一個新函數。

0

由於您的邊界上下文。你可以使用箭頭函數或this.timer.bind(this)

相關問題