javascript - react native : _this2. setState不是一个函数

标签 javascript react-native

我有一个在单击按钮时起作用的函数。 在我添加 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/

相关文章:

javascript - 当输入焦点或已填充时显示 div jquery

c# - Appcache 文件未更新

javascript - Visual Studio Asp.net core Angular 模板在构建时自动运行测试

css - 在 React Native 中将按钮设置在位置 "fixed"

reactjs - React - 来自 API 的值不会出现在 View 中

javascript - 显示 div 一段时间,然后隐藏它

javascript - SoundManager2 有哪些好的替代品?

react-native - React Native 内联样式与 Stylesheet.create

javascript - 如何使用 redux React Native 添加拉动刷新

javascript - 在 react-native 中迭代 JSON 数组