在 React Redux 应用程序中检测网络连接 - 如果离线,则对用户隐藏组件

Detect network connection in React Redux app - if offline, hide component from user

我正在使用 google 的自动完成功能 API 来改进我表单中的地址输入。

我正在使用 GoogleMapsLoader 加载器,它会在加载后分派操作:

GoogleMapsLoader.onLoad(function() {
    store.dispatch(GoogleActions.loaded());
});

在 React 组件中我有以下输入:

if (google.status === 'LOADED') {
    inputGoogle = <div>
        <label htmlFor={`${group}.google`}>Auto Complete:</label>
        <input ref={(el) => this.loadAutocomplete(el)} type="text" />
    </div>;
} else {
    inputGoogle = '';
}

loadAutocomplete 方法(不确定这是否是最好的方法):

loadAutocomplete(ref) {
    if (!this.autocomplete) {
        this.search = ref;
        this.autocomplete = new google.maps.places.Autocomplete(ref);
        this.autocomplete.addListener('place_changed', this.onSelected);
    }
},

更新:

使用下面的答案我做了以下操作:

const GoogleReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'GOOGLE_LOADED':
            return Object.assign({}, state, {
                status: 'LOADED',
                connection: 'ONLINE'
            });
        case 'GOOGLE_OFFLINE':
            return Object.assign({}, state, {
                connection: 'OFFLINE'
            });
        case 'GOOGLE_ONLINE':
            return Object.assign({}, state, {
                connection: 'ONLINE'
            });
        default:
            return state;
    }
};

const GoogleActions = {
    loaded: () => {
        return (dispatch) => {
            dispatch({
                type: 'GOOGLE_LOADED',
            });
        };
    },
    onOnline: () => {
        return (dispatch) => {
            window.addEventListener('online', function() {
                dispatch({
                    type: 'GOOGLE_ONLINE'
                });
            });
        };
    },
    onOffline: () => {
        return (dispatch) => {
            window.addEventListener('offline', function() {
                dispatch({
                    type: 'GOOGLE_OFFLINE'
                });
            });
        };
    }
};

内部 React 组件:

if (google.status === 'LOADED' && google.connection === 'ONLINE') {
    inputGoogle = <div>
        <label htmlFor={`${group}.google`}>Auto Complete:</label>
        <input ref={(el) => this.loadAutocomplete(el)} name={`${group}.google`} id={`${group}.google`} type="text" onFocus={this.clearSearch}/>
    </div>;
} else {
    inputGoogle = <p>Auto Complete not available</p>;
}

到目前为止有效。

你可以使用 Navigator 对象的 onLine 方法,returns 布尔值,true 如果在线,那么只需在你的 react render 中添加一条语句。

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

render(){
    var input = navigator.onLine ? <YOUR_FORM_COMPONENT> : null;
    return(
    <div>
        {input}
    </div>
    )    
}

navigator.onLine 将 return 状态,无论是 在线还是离线 但它不会检查 internet connectivity 有没有。 向@StackOverMySoul 添加更多内容。要摆脱这个可以参考下面的例子。

    var condition = navigator.onLine ? 'online' : 'offline';
    if (condition === 'online') {
      console.log('ONLINE');
        fetch('https://www.google.com/', { // Check for internet connectivity
            mode: 'no-cors',
            })
        .then(() => {
            console.log('CONNECTED TO INTERNET');
        }).catch(() => {
           console.log('INTERNET CONNECTIVITY ISSUE');
        }  )

    }else{
       console.log('OFFLINE')
    }

为什么选择google.com?

将 get 请求发送到 google.com 而不是任何随机平台的原因是因为它有很好的正常运行时间。这里的想法是始终将请求发送到始终在线的服务。如果你有一台服务器,你可以创建一个专用路由来代替 google.com 域,但你必须确保它有一个惊人的正常运行时间。

使用navigator.onLine检查网络连接。如果网络连接可用,则 return 为真,否则 return 为假。

也尝试使用navigator.connection验证网络连接状态。

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if (connection) {
      if (connection.effectiveType === 'slow-2g')
        preloadVideo = false;
    }

更多Network Information API

我一直在使用 react-detect-offline 来处理显示 online/offline 特定内容,它处理不支持带轮询的在线事件的旧浏览器,您可以在 URL 中指定轮询选项。

https://github.com/chrisbolin/react-detect-offline

首先安装包

npm install react-detect-offline

然后在你的组件中你会做类似

的事情
import { Offline, Online } from "react-detect-offline"

const MyComponent = () => {
    return (
        <div>
            <Offline>You're offline right now. Check your connection.</Offline>
            <Online>You're online right now.</Online>
        </div>
    );
}

对于 reacttypescript 编码人员:这个人有简单且可重复使用的解决方案 https://medium.com/@vivekjoy/usenetwork-create-a-custom-react-hook-to-detect-online-and-offline-network-status-and-get-network-4a2e12c7e58b

很适合我。

您可以创建自定义挂钩并尝试每五秒发送一次请求:

import { useState, useEffect } from 'react';

const useNetworkStatus = () => {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    const interval = setInterval(() => {
      fetch('https://www.google.com/', {
        mode: 'no-cors',
      })
        .then(() => !isOnline && setIsOnline(true))
        .catch(() => isOnline && setIsOnline(false));
    }, 5000);

    return () => clearInterval(interval);
  }, [isOnline]);

  return { isOnline };
};

export default useNetworkStatus;

然后像这样使用它:

import useNetworkStatus from '@/hooks/useNetworkStatus';
// ...
const { isOnline } = useNetworkStatus();