首页 > 解决方案 > How do I specifically check a URL with NetInfo React-Native?

问题描述

This is the code you are currently using to exchange and verify a connection, I think it is working fine:

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

How do I check a URL? I thought about using it now, but I could not implement it

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

sorry for this, i'm new with reacting native

标签: react-nativereact-native-androidreact-native-ios

解决方案


fetch 返回承诺,

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

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

推荐阅读