我有一个在单击按钮时起作用的函数。 在我添加 setInterval 方法之前,该函数运行良好,添加它之后,它显示错误:_this2.setState 不是函数
这是函数:
getWifiNetworksOnPress() {
setInterval(function timer() {
console.log("hello world");
wifi.loadWifiList(
wifiStringList => {
console.log(wifiStringList);
var wifiArray = JSON.parse(wifiStringList);
this.setState({
wifiList: wifiArray
});
},
error => {
console.log(error);
}
);
}, 3000);
}
这是按钮:
<Button onPress={this.getWifiNetworksOnPress.bind(this)}>
get location
</Button>
我找到的这个问题的所有答案都是将 .bind(this) 添加到 onPress,但它不起作用。知道如何解决这个问题吗?
最佳答案
为什么不在 setInterval 函数中使用粗箭头函数? 这应该有效:
getWifiNetworksOnPress = () => {
setInterval(() => {
console.log("hello world");
wifi.loadWifiList(wifiStringList => {
console.log(wifiStringList);
var wifiArray = JSON.parse(wifiStringList);
this.setState({
wifiList: wifiArray
});
}, error => {
console.log(error);
});
}, 3000);
}
还有
<Button onPress={this.getWifiNetworksOnPress}>
Search Networks
</Button>
关于javascript - react native : _this2. setState不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56782398/