检测React Redux应用程序中的网络连接 - 如果脱机,则隐藏用户的组件

The*_*ion 9 javascript reactjs redux react-redux

我正在使用谷歌的自动完成API来改善我的表单中的地址输入.

我正在使用GoogleMapsLoader加载器,它在加载后调度操作:

GoogleMapsLoader.onLoad(function() {
    store.dispatch(GoogleActions.loaded());
});
Run Code Online (Sandbox Code Playgroud)

在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 = '';
}
Run Code Online (Sandbox Code Playgroud)

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

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

更新:

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

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'
                });
            });
        };
    }
};
Run Code Online (Sandbox Code Playgroud)

里面的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>;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止工作.

Jos*_*osh 13

我一直在使用 React-Detect-Offline 来处理显示在线/离线特定内容,它可以处理不支持轮询在线事件的旧浏览器,并且您可以在选项中指定轮询 URL。

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

首先安装包

npm install react-detect-offline
Run Code Online (Sandbox Code Playgroud)

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

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>
    );
}
Run Code Online (Sandbox Code Playgroud)


Sta*_*oul 12

你可以使用Navigator对象的onLine方法,返回一个布尔值,true如果在线,那么只需在你的反应渲染中添加一个语句.

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

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

  • 好的反应回购主要以正确的方式处理问题:https://github.com/chrisbolin/react-detect-offline/blob/master/src/index.js (3认同)
  • 不幸的是,这在浏览器中并不一致,或者可靠.在任何页面中尝试,在控制台中输入`navigator.onLine`.它应该说'真实'.关掉你的wifi.点击控制台中的向上箭头以重复上一个命令.它仍然会说"真实".它没有调查您的实际网络连接.它正在查看浏览器的`onLine`变量,这是最好的. (2认同)

Mah*_*rus 6

navigator.onLine将返回状态是否在线或离线,但不会检查互联网连接是否存在。向@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')
    }
Run Code Online (Sandbox Code Playgroud)

为什么选择 google.com?

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