美文网首页
reactNative中监听网络变化

reactNative中监听网络变化

作者: vivianXIa | 来源:发表于2021-01-22 23:59 被阅读0次

步骤一:添加插件

yarn add @react-native-community/netinfo
//AndroidManifest.xml中添加如下权限请求
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

步骤二 添加文件

具体代码

import NetInfo from '@react-native-community/netinfo'

// Subscribe to network state updates:监听网络更新
const unsubscribe = NetInfo.addEventListener(state => {
  console.log({"网络状态1+++++++++++++++++++":state});
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

//Get the network state once:单次获取网络状态
const getNetWork = ()=>{
  NetInfo.fetch().then(state => {
    console.log({"网络状态2+++++++++++++++++++":state});
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
  });
}

module.exports = {
  unsubscribe,
  getNetWork
}

步骤三

在页面上引入文件

//这里是一个网络监听 如果是单次获取则使用getNetWork
import { subscribe } from '../common/netWork';

//比如在页面挂载完毕的时候去添加网络监听 其它地方就可以读取网络情况啦
    subscribe((res) => {
      console.log("网络+++++++++++++++++", res.isConnected);
      $this.setState({
        interNetCon: res.isConnected
      })

相关文章

网友评论

      本文标题:reactNative中监听网络变化

      本文链接:https://www.haomeiwen.com/subject/npkyzktx.html