2016-05-24 73 views
1

當我點擊調用_handlePressStartStop()函數的按鈕時,出現一個關於setState的錯誤。它講述:setState不工作setInterval In React

**(intermediate value).bind is not a function** 

我知道我有麻煩這個,也許是我的問題的根源。這裏是我的代碼:

class StopWatch extends Component { 

constructor(props) { 
    super(props); 

    this.state = { 
    startTime: null, 
    timeElapsed: null 
    }; 
} 

render() { 
    return (
    <View style={styles.container}> 
     <View style={styles.header}> 
     <View style={styles.counter}> 
      <Text style={styles.counterText}>{this.state.timeElapsed}</Text> 
     </View> 
     <View style={styles.buttonsWrapper}> 
      <Button buttonType='startStop' onPress={this._handlePressStartStop}>Start</Button> 
      <Button buttonType='lap' onPress={this._handlePressLap}>Lap</Button> 
     </View> 
     </View> 
     <View style={styles.footer}> 
     </View> 
    </View> 
) 
} 

_handlePressStartStop() { 
    console.log("press start"); 

    let startTime = new Date(); 

    setInterval(() => { 
     this.setState({ 
     timeElapsed: new Date() - startTime 
     }.bind(this)) 
    }, 1000); 

} 

_handlePressLap() { 
    console.log("press lap"); 
} 

}

+0

對象不具有'.bind'方法。這就是錯誤告訴你的。 '{...}。bind(this)'簡直是無效的。 –

+0

相關:[如何在回調中訪問正確的'this'/context?](http://stackoverflow.com/q/20279484/218196) –

回答

2

你不會想綁定到該這樣。你綁定的對象是無效的。你如何約束處理器

onPress={this._handlePressStartStop}.bind(this)取而代之?

這種方式,處理程序函數內部執行一切將具有相同this(一個反應組件實例)

+1

謝謝,它的工作! –

0

嘗試 this._handlePressStartStop.bind(this)