互联网连接侦听器

Internet Connection Listener

我有一个扫描二维条形码然后从代码提供的 URL 中检索数据的应用程序。如果用户失去与 Internet 的连接,应用程序将开始通过 AsyncStorage 存储 URL。问题是,我需要实现一个侦听器,在重新获得 Internet 连接后,应用程序将开始一个给定的方法。是否有任何推荐的方法来实现这样的连接侦听器?

编辑:
我尝试过使用 NetInfo EventListener,但是我不确定我是否使用不当,因为它总是调用传递的函数,即使互联网状态没有改变。

_connectionHandler = (e) => {
    this.setState({ cameraActive: false })
    NetInfo.getConnectionInfo().then((connectionInfo) => {

        if (connectionInfo.type === "none"){
            console.log("No internet")
            dataArray.push(e.data)
            let barcodeData_delta = {
                data: dataArray
            }

            AsyncStorage.mergeItem(STORAGE_KEY, JSON.stringify(barcodeData_delta));

            NetInfo.isConnected.addEventListener(
                'connectionChange',
                this._handleConnectionChange(e.data)
            );
            this.setState({ cameraActive: true })
        } else {
            console.log("Internet available -> Going to read barcode now")
            this._handleBarCodeRead(e.data);
        }
    })
}

React Native 有一个 NetInfo 文档,在那里你可以看到如何为他的连接变化添加一个监听器,并在它被调用时做你想做的事情。

向 isConnected 添加处理程序 属性

NetInfo.isConnected.addEventListener(
  'connectionChange',
  _connectionHandler
);

一个处理变化的函数,只是用相机调整你的setState,我不知道什么时候调用它。

_connectionHandler = (isConnected) => {
    this.setState({ cameraActive: false })
        if (!isConnected){
            console.log("No internet")
            dataArray.push(e.data)
            let barcodeData_delta = {
                data: dataArray
            }
            AsyncStorage.mergeItem(STORAGE_KEY, JSON.stringify(barcodeData_delta));                   
            this.setState({ cameraActive: true })
        } else {
            console.log("Internet available -> Going to read barcode now")
            this._handleBarCodeRead(e.data);
        }
    })
}