【问题标题】:How to check the internet reachability in React-native?如何在 React-native 中检查互联网可达性?
【发布时间】:2019-08-20 06:49:29
【问题描述】:

我已经尝试@react-native-community/netinfo 来检查互联网的可达性。但我要实现的场景是,假设我的设备从另一台设备连接到 wifi 热点,并且如果该设备的移动数据已关闭,我想显示离线 toast。

componentDidMount() {
 NetInfo.addEventListener(status => {
  this.props.checkOnlineStatus(
    status.isConnected,
    status.isInternetReachable
  );
  this.setState({
    isConnected: status.isConnected,
    isInternetReachable: status.isInternetReachable
  });
 });
}

render() {
 if (!this.state.isInternetReachable && this.props.isOfflineNoticeVisible) {
  return <MiniOfflineSign />;
 }
 return null;
}

但在这种情况下,当其他设备的移动数据关闭时,它不会处理更改。

【问题讨论】:

    标签: react-native react-native-android react-native-community-netinfo


    【解决方案1】:

    @react-native-community/netinfo 包的非弃用方式(使用功能组件)现在是:

    import React, { useEffect } from "react";
    import NetInfo from "@react-native-community/netinfo";
    
      useEffect(() => {
        return NetInfo.addEventListener(state => {
          // use state.isInternetReachable or some other field
          // I used a useState hook to store the result for use elsewhere
        });
      }, []);
    

    这将在状态更改时运行回调,并在组件卸载时取消订阅。

    【讨论】:

      【解决方案2】:

      这些连接类型可能会有所帮助:https://github.com/react-native-community/react-native-netinfo#netinfostatetype

      否则:

      那么可以肯定的是,你在线只需实现一个超时获取:

       export default function(url, options, timeout = 5000) {
            return Promise.race([
              fetch(url, options),
              new Promise((_, reject) => setTimeout(() => reject("timeout"), timeout)),
            ]);
          }
      

      然后像这样使用它:

      fetchWithTimeout(url, options)
              .then(resp => {
                if (resp.status === 200) {
                  let json = resp.json().then(j => {
                    return j;
                  });
              })
              .catch(ex => {
                // HANDLE offline usage
                if (ex === "timeout") return true;
                //ANY OTHER CASE RETURN FALSE
                return false;
      }
      

      【讨论】:

        【解决方案3】:

        async function InternetCheck() {
            const connectionInfo = await NetInfo.getConnectionInfo();
            if (connectionInfo.type === 'none') {
                alert('PLEASE CONNECT TO INTERNET');
            } else {
                    //navigate to page or Call API
            }
        }

        【讨论】:

        • 不幸的是,它触发了 2 个事件,一个是 type='wifi',一个是 'none'。这会导致我们的处理程序出现问题,因为它会触发不应触发的副作用(对于不应该存在的第一个事件)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 1970-01-01
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多