在React Redux应用程序中检测网络连接-如果离线,则向用户隐藏组件 [英] Detect network connection in React Redux app - if offline, hide component from user
问题描述
我正在使用Google的自动填充API来改进表单中的地址输入.
I am using google's autocomplete API to improve address input in my form.
我正在使用GoogleMapsLoader加载程序,该加载程序在加载后立即分派动作:
I am using GoogleMapsLoader loader which dispatches action once loaded:
GoogleMapsLoader.onLoad(function() {
store.dispatch(GoogleActions.loaded());
});
在React组件中,我有以下输入内容:
In React component I have following input:
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方法(不确定这是否是最好的方法):
the loadAutocomplete method (not sure if it is best way of doing that) :
loadAutocomplete(ref) {
if (!this.autocomplete) {
this.search = ref;
this.autocomplete = new google.maps.places.Autocomplete(ref);
this.autocomplete.addListener('place_changed', this.onSelected);
}
},
更新:
使用下面的答案,我做了以下事情:
UPDATE:
Using answer below I did following:
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方法,如果在线则返回布尔值, true
,然后只需在您的计算机上添加一条语句即可.反应渲染.
you can use the onLine method of the Navigator object, returns a boolean, true
if online, then just add a statement in your react render.
https://developer.mozilla.org/zh-US/docs/Web/API/NavigatorOnLine/onLine
render(){
var input = navigator.onLine ? <YOUR_FORM_COMPONENT> : null;
return(
<div>
{input}
</div>
)
}
这篇关于在React Redux应用程序中检测网络连接-如果离线,则向用户隐藏组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!