我在我的代码中使用Net-info来检查Internet连接,但它对我不起作用。会报错..
类型错误:未定义不是对象(正在评估'_reactNative.Netinfo.isConected')
我还在AndroidManifest.xml中设置了权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
但这对我不起作用
我的代码在这里。
import { StyleSheet, Text, View, NetInfo } from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state={
connection_Status : ""
}
}
componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done((isConnected) => {
if(isConnected == true)
{
this.setState({connection_Status : "Online"})
}
else
{
this.setState({connection_Status : "Offline"})
}
});
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'connectionChange',
this._handleConnectivityChange
);
}
_handleConnectivityChange = (isConnected) => {
if(isConnected == true)
{
this.setState({connection_Status : "Online"})
}
else
{
this.setState({connection_Status : "Offline"})
}
};
render() {
return (
<View style={styles.MainContainer}>
<Text style={{fontSize: 20, textAlign: 'center', marginBottom: 20}}> You are { this.state.connection_Status } </Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding: 20
},
TextStyle: {
fontSize:20,
textAlign: 'center'
}
});
如何解决此问题,请提出任何解决方案。
答案 0 :(得分:1)
我不知道您拥有什么版本的React Native,但是netinfo已被提取到另一个库中。
https://github.com/react-native-community/react-native-netinfo
答案 1 :(得分:0)
您必须更改 const { 视图, ImageBackground, 活动指示器 NetInfo, 平台, StyleSheet, } = ReactNative;
到
const { 视图, ImageBackground, 活动指示器 平台, StyleSheet, } = ReactNative;
const NetInfo = require('@ react-native-community / netinfo'); 在node-module / react-native-cached-image / CachedImage.js
答案 2 :(得分:0)
对于2021年尝试使用这个的人来说,netinfo和react native是分开的,需要从这里分开导入: https://github.com/react-native-netinfo/react-native-netinfo
如果使用还是报错,可能是fetch折旧了,不用了
componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done((isConnected) => {
if(isConnected == true)
{
this.setState({connection_Status : "Online"})
}
else
{
this.setState({connection_Status : "Offline"})
}
});
}
改为使用这个
componentDidMount() {
NetInfo.addEventListener(this.handleConnectivityChange);
// The fetch is not needed as the listen will send the current state when you subscribe to it
}
componentWillUnmount() {
NetInfo.removeEventListener(this.handleConnectivityChange);
}
handleConnectivityChange = state => {
if (state.isConnected) {
Alert.alert('online');
this.setState({connection_Status: 'Online'});
} else {
Alert.alert('offline');
this.setState({connection_Status: 'Offline'});
}
};
正如在这个github中提到的 https://github.com/react-native-netinfo/react-native-netinfo/issues/279