当我从真实设备上关闭互联网连接时,它没有检测到我处于离线状态,但是当再次上线时,它会将值返回为 true。
import React from 'react';
import {
SafeAreaView,
StyleSheet,
View,
Text,
StatusBar,
Image,
TouchableOpacity,
FlatList,
NetInfo
} from 'react-native';
export default class App extends React.Component {
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange',
this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange',
this.handleConnectivityChange);
}
handleConnectivityChange = (isConnected) => {
console.log(isConnected ? 'connected':'not connected')
}
到目前为止,我没有在这里提到 render()。
最佳答案
使用 React Native Community's NetInfo
因为 RN's version is deprecated .
RNC 版本仅在添加监听器时接受回调。
它应该是:
import NetInfo from "@react-native-community/netinfo";
export default class App extends React.Component {
constructor(props) {
super(props)
this.unsubscribe = null
}
componentDidMount() {
this.unsubscribe = NetInfo.addEventListener(
this.handleConnectivityChange
);
}
componentWillUnmount() {
this.unsubscribe();
}
handleConnectivityChange = (state) => {
console.log(state.isConnected ? 'connected': 'not connected')
}
render() {...}
}
关于reactjs - 当我关闭互联网连接时,它没有显示来自 NetInfo.isConnect 函数的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766348/