1

react-native-netinfo用来跟踪我的设备的互联网连接。在互联网断开连接并重新启动之前,它大部分时间都运行良好。此时NetInfo不会以正确的 Internet 状态响应。

在查看 github 上的 repo 时,看起来这是一个尚未修复的已知问题。在其中一个线程中,提到了使用钩子useNetInfo而不是因为显然仍然可以正常工作。

所以我尝试了这里提到的https://github.com/react-native-netinfo/react-native-netinfo/issues/400#issuecomment-953177841但即使这在建立连接时也没有返回正确的状态再次。

我不知道现在该怎么办。我不知道这个钩子是否还有更多内容,或者是否需要以不同的方式实现。

4

1 回答 1

0

我所做的是在 componentDidMount() 中添加一个事件侦听器并在componentWillUnMount ()中删除该侦听器。

componentDidMount(){
 NetInfo.isConnected.fetch().then(isConnected => {
                this.handleConnectivityChange(isConnected === undefined ? true : isConnected);
            });
            NetInfo.isConnected.addEventListener(
                'connectionChange',
                this.handleConnectivityChange
            );}

我的 handleConnectivityChange() 函数将 isConnected 布尔值存储在 redux 中,以便在我想要的任何地方使用。

componentWillUnMount() {
NetInfo.isConnected.removeEventListener(
            'connectionChange',
            this.handleConnectivityChange
        );
}
于 2021-11-26T07:44:31.787 回答