netInfo React Native总是在ios模拟器中返回false

NetInfo.isConnected.fetch().then(isConnected => {
    if (isConnected == true) {
        this.setState({isOnline: true})
        this.checkForToken()
    }
    else {
        this.setState({isOnline: false})
        this.checkTokenOffline()
    }
});

NetInfo.isConnected.fetch().then().done(() => {
    NetInfo.isConnected.addEventListener('connectionChange', (isConnected) => this.dispatchConnected());
})

最佳答案

这是known bug,它总是给出false。您需要附加一个侦听器,然后使用它。

yourFunction = () => {
    NetInfo.isConnected.fetch().then(isConnected => {
        //Always false, so ignore/do nothing here
    });
    NetInfo.isConnected.addEventListener(
        'connectionChange',
        this.handleFirstConnectivityChange
    );
}

handleFirstConnectivityChange = (isConnected) => {
    if (isConnected == true) {
        this.setState({isOnline: true})
        this.checkForToken()
    }
    else {
        this.setState({isOnline: false})
        this.checkTokenOffline()
    }
}

10-07 19:08