如何使用NetInfo React-Native专门检查URL?

时间:2019-02-19 03:26:59

标签: react-native react-native-android react-native-ios

这是您当前用于交换和验证连接的代码,我认为它工作正常:

  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." })
      }
    });
    SplashScreen.hide();
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener(
      'connectionChange',
      this._handleConnectivityChange
    );
  }

  _handleConnectivityChange = (isConnected) => {
    if (isConnected == true) {
      this.setState({ connection_Status: "Online" })
    }
    else {
      this.setState({ connection_Status: "Offline." })
    }
  };

如何检查URL? 我考虑过现在使用它,但无法实现

let req = await fetch('https://www.someurl.com'); let isConnected = req.status === 200;

对此感到抱歉,我是新来的本地人

1 个答案:

答案 0 :(得分:0)

获取返回承诺,

因此您可以像这样使用它,

fetch('https://www.someurl.com')
 .then((res) =>{
        this.setState({status:res.status});
     })
    .then((res) => {
      //do somthing with responce
    })
    .catch((error) => {
      console.error(error);
    });