web-dev-qa-db-ja.com

ネットワークがオフのときにReact-Nativeでネットワーク障害を処理する方法

デバイスがネットワークに接続されていないときに、React-Nativeでネットワーク障害を処理する方法。

私のシナリオは、ネットワークが切断されている場合に要求をフェッチしているときにAPIを接続しようとしていますが、ネイティブ応答がスローされ、ネットワーク要求が失敗しましたこのシナリオを処理して、ユーザーに最高のユーザーエクスペリエンスを提供する方法。

ネットワークリクエストの処理方法が失敗しました。

enter image description here

12
rakesh r

次のように NetInfo を使用します。

// Check for network connectivity
NetInfo.isConnected.fetch().done((isConnected) => {
    if ( isConnected )
    {
        // Run your API call
    }
    else
    {
        // Ideally load from local storage
    }
});
9
Ryan Marshall

Catchブロックを使用して例外を処理します。catchブロックから、例外を処理するアクションを実行できます。リダイレクトまたは状態変更でエラーを表示できます。

const url = `your url to be fetched`;
        fetch(url, {
          method: "GET",
          headers: header
        })
          .then(res => res.json())
          .then(json => {
            console.log(json);
             this.setState({
                data:json
              });  
    })
    .catch(error => {
      if (error) {
        //perform the redirection to the network request slow page or set state to show error
      }
    });
1
Nandagopan PB

これを試して、fetch()でエラーを処理できます。

// Handling Internet Errors


handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
  }


fetch(/*"url"*/)
  .then(this.handleErrors)
  .then(response => console.log("ok") )
  .catch(error => console.log(error) );
0
AndroConsis