首页 > 解决方案 > 根据外部 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 资源时才考虑在线。

标签: javascriptreactjsaxios

解决方案


您可以使用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.");
});

推荐阅读