我需要在我的应用中检查用户与互联网的连接。我尝试使用NetInfo 但我收到此错误:
无法读取未定义的属性'isConnected'
我还在AndroidManifest.xml
文件中添加了权限,但这无济于事。
这是我的代码:
NetInfo.isConnected.fetch().then(isConnected => {
if (isConnected) {
this.setState({
loading: true,
})
var url = 'https://api.apixu.com/v1/current'+this.state.cityname
return fetch(url)
.then((data) => data.json())
.then((datajson) => {
this.setState({
loading: false,
fetched: true,
})
console.log(this.state.localtime)
})
.catch((error) => { console.error(error) })
} else {
Alert.alert("You are offline!");
}
是什么原因导致此问题?
答案 0 :(得分:0)
import {NetInfo} from 'react-native';
constructor(props) {
super(props);
this.state = {
isNetConnected: true,
}
}
async componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done((isConnected) => {
if(isConnected == true)
{
this.setState({isNetConnected: true})
}
else
{
this.setState({isNetConnected: false})
}
});
}
_handleConnectivityChange = (isConnected) => {
if(isConnected == true)
{
this.setState({isNetConnected: true})
this.getActivitiesAndNotifications()
}
else
{
this.setState({isNetConnected: false})
}
};
使用像这样。现在,如果没有任何互联网连接,“ isNetConnected”将触发