gpt4 book ai didi

reactjs - react-native - 无法访问组件函数内的 setState

转载 作者:行者123 更新时间:2023-12-03 13:33:55 24 4
gpt4 key购买 nike

我正在学习react-native,现在我因以下错误而陷入状态类(class):

_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);
}
...

我做错了什么?

最佳答案

handleStartStopClick 是从 this 不是您的类实例的上下文中调用的。您可以通过将 .bind(this) 添加到作为点击处理程序传递的函数来避免这种情况。

<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>

关于reactjs - react-native - 无法访问组件函数内的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com