我具有单击按钮时起作用的功能。
在添加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>


我为该问题找到的所有答案都是在.onPress中添加.bind(this),但无法正常工作。任何想法如何解决这个问题?

最佳答案

尝试使用const _this添加对类的引用,例如以下代码:

getWifiNetworksOnPress() {
   const this_ = this;
   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);
}

关于javascript - react native :_this2.setState不是函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56782398/

10-10 00:27
查看更多