javascript - 根据外部 Internet 连接动态更改状态 - React(离线/在线)
问题描述
我有一个 React 组件,其中包括 Internet 连接的可用性标志。UI 元素必须根据状态实时动态改变。此外,随着标志的变化,函数的行为也会有所不同。
我当前的实现使用间隔每秒使用Axios轮询远程 API ,并相应地更新状态。我正在寻找一种更精细、更有效的方法来完成这项任务,以最小的计算成本消除 1 秒的状态错误。当且仅当设备具有外部 Internet 连接时才考虑在线
当前实施:
class Container extends Component {
constructor(props) {
super(props)
this.state = {
isOnline: false
};
this.webAPI = new WebAPI(); //Axios wrapper
}
componentDidMount() {
setInterval(() => {
this.webAPI.poll(success => this.setState({ isOnline: success });
}, 1000);
}
render() {
return <ChildComponent isOnline={this.state.isOnline} />;
}
}
编辑:
寻找能够检测外部 Internet 连接的解决方案。该设备可以连接到没有外部连接的 LAN。所以,它被认为是离线的。当且仅当设备可以访问外部 Internet 资源时才考虑在线。
解决方案
您可以使用https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event
window.addEventListener('offline', (event) => {
console.log("The network connection has been lost.");
});
和https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event 检查您何时重新上线
window.addEventListener('online', (event) => {
console.log("You are now connected to the network.");
});
推荐阅读
- javascript - 在可排序更改上更新 javascript 对象中的位置
- html - 内容的可见性在移动视图中非常小
- java - 我们可以在不同的端口上运行 Spring REST API 吗?
- php - 使用 php 从内爆数据中删除第一个字符
- javascript - 为什么尝试启动 Mongo 服务器时 Nodemon 服务器崩溃?
- android - 如何在适用于 Android 的 Google Analytics (v4) 中获取广告系列数据?
- python - 如何使用从另一个文件python导入的变量的值
- spring-boot - Springboot 摘要认证支持
- ruby-on-rails - Rspec:如何测试在私有方法中引发的异常?
- java - 将 Netbeans 预捆绑的库添加到 Fresh Maven 项目