React Native使用NetINFO检查网络连接

5
我在我的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;
1个回答

5
我能够重现您的错误,并且通过将 componentWillMount 改为 componentDidMount 使其正常工作。我认为 React 在调用 this.setState 时出现了内部错误,因为组件尚未挂载(因此无法重新渲染任何内容)。
希望这可以帮到您 :)

真的!新版本的React已经放弃了componentWillMount方法。 - twboc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接