setState 在 React 中的 setInterval 中不起作用
setState Is not Working Inside setInterval In React
当我单击调用 _handlePressStartStop() 函数的按钮时,出现有关 setState 的错误。它告诉:
**(intermediate value).bind is not a function**
我知道我在 this 方面遇到了麻烦,也许这是我问题的根源。这是我的代码:
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");
}
}
试试看
this._handlePressStartStop.bind(this)
你不会想像那样绑定到这个。您将对象绑定到无效的对象。你如何绑定处理程序
onPress={this._handlePressStartStop}.bind(this)
而不是?
这样,处理函数内执行的所有内容都将具有相同的this
(一个反应组件实例)
当我单击调用 _handlePressStartStop() 函数的按钮时,出现有关 setState 的错误。它告诉:
**(intermediate value).bind is not a function**
我知道我在 this 方面遇到了麻烦,也许这是我问题的根源。这是我的代码:
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");
}
}
试试看
this._handlePressStartStop.bind(this)
你不会想像那样绑定到这个。您将对象绑定到无效的对象。你如何绑定处理程序
onPress={this._handlePressStartStop}.bind(this)
而不是?
这样,处理函数内执行的所有内容都将具有相同的this
(一个反应组件实例)