react-native - 无法在组件函数中访问 setState
react-native - can't access setState inside component function
我正在学习 react-native,现在我因为这个错误而卡在状态课上:
_this2.setState is not a function.
这是当前的代码块。
...
export default class StopWatch extends Component {
constructor(props){
super(props);
this.state = {
timeElapsed: null
}
}
handleStartStopClick(){
var startTime = new Date();
setInterval(() => {
this.setState(previousState => {
return {timeElapsed:new Date() - startTime};
});
}, 100);
}
...
我做错了什么?
试试这个:
this.setState({timeElapsed : (new Date() - startTime)})
您必须在构造函数中使用 bind(this) 或
定义您的函数
handleStartStopClick = () => {...}
handleStartStopClick
是从 this
不是您的 class 实例的上下文中调用的。您可以通过将 .bind(this)
添加到作为点击处理程序传递的函数来避免这种情况。
<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>
我正在学习 react-native,现在我因为这个错误而卡在状态课上:
_this2.setState is not a function.
这是当前的代码块。
...
export default class StopWatch extends Component {
constructor(props){
super(props);
this.state = {
timeElapsed: null
}
}
handleStartStopClick(){
var startTime = new Date();
setInterval(() => {
this.setState(previousState => {
return {timeElapsed:new Date() - startTime};
});
}, 100);
}
...
我做错了什么?
试试这个:
this.setState({timeElapsed : (new Date() - startTime)})
您必须在构造函数中使用 bind(this) 或
定义您的函数handleStartStopClick = () => {...}
handleStartStopClick
是从 this
不是您的 class 实例的上下文中调用的。您可以通过将 .bind(this)
添加到作为点击处理程序传递的函数来避免这种情况。
<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>