當我點擊調用_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");
}
}
對象不具有'.bind'方法。這就是錯誤告訴你的。 '{...}。bind(this)'簡直是無效的。 –
相關:[如何在回調中訪問正確的'this'/context?](http://stackoverflow.com/q/20279484/218196) –