我在我的react-native v0.49应用程序上实现了检查互联网. 我正在使用反应原生的NetInfo. 我在发生任何更改时添加了eventListener,它将调用函数. 但是当我在模拟器和真实设备中进行测试时,我只
我正在使用反应原生的NetInfo.
我在发生任何更改时添加了eventListener,它将调用函数.
但是当我在模拟器和真实设备中进行测试时,我只得到第一个更改,但如果我从Wifi断开连接,我看不到任何变化.
internetConnectionPopUp
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;
我可以重现您的错误,它适用于我将componentWillMount更改为componentDidMount.我认为React有一个内部错误调用this.setState,因为组件尚未挂载(所以它可以重新渲染任何东西).
希望能帮助到你 :)
