我在我的React Native v0.49应用程序中实现了检查互联网的功能。使用React Native的NetInfo库。当任何更改发生时,我添加一个事件侦听器来调用函数。但是,当我在模拟器和真实设备上测试它时,我只得到第一次更改,但如果我断开Wifi连接,我就看不到任何更改。
互联网连接弹出窗口。
互联网连接弹出窗口。
import React, { Component } from 'react';
import {
View,
Text,
NetInfo
} from 'react-native';
// styles
import { style } from './style';
import { globalStyle } from '../../assets/styles/globalStyle';
// redux
import {connect} from 'react-redux';
import * as actions from '../../actions';
class InternetConnectionPopUp extends Component {
constructor(props){
super(props);
this.state = {
connectionInfo : ''
}
this.handleFirstConnectivityChange = this.handleFirstConnectivityChange.bind(this);
}
handleFirstConnectivityChange(connectionInfo) {
this.setState({
connectionInfo: connectionInfo.type
})
console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
}
componentWillMount () {
NetInfo.getConnectionInfo().then((connectionInfo) => {
this.setState({
connectionInfo: connectionInfo.type
})
//console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
});
NetInfo.addEventListener(
'connectionChange',
this.handleFirstConnectivityChange
);
}
componentWillUnmount() {
NetInfo.removeEventListener(
'connectionChange',
handleFirstConnectivityChange
);
}
render() {
return (
<View>
<Text> ComponentName component </Text>
<Text> { this.state.connectionInfo } </Text>
</View>
);
}
}
export default InternetConnectionPopUp;