React Native中的NetInfo使用模式

时间:2020-07-22 17:08:51

标签: javascript react-native react-native-community-netinfo

我试图在我的React Native应用程序中创建一个健壮的模式,以便如果没有Internet连接,我将不会进行API调用,而是显示“连接丢失...”消息。

我创建了以下util函数,并尝试使用fetch将其合并到我的API调用中,但是在获得响应后,它似乎未达到then块。

以下是检查连接的功能:

import NetInfo from "@react-native-community/netinfo";

export const isConnectedToInternet = () => {

   NetInfo.fetch().then(state => {
      return state.isConnected;
    });
};

这是我尝试使用它的方式:

import { isConnectedToInternet } from '../my-utils';

export const someApiCall = () => {

   isConnectedToInternet()
      .then(result => {

         if(result) {
          
             return (dispatch) => fetch ('https://myapi/someendpoint', fetchOptionsGet())
                               .then(response => {

                                  // Process data...
                               })
         } else {
    
             Alert.alert('No Internet connection!');
         }
   })
};

有什么主意为什么我没有碰到then块或建议使它成为一个健壮的模式?

2 个答案:

答案 0 :(得分:2)

如果您想在isConnectedToInternet上加上然后,则应使其兑现承诺。尝试这样的事情:

import NetInfo from "@react-native-community/netinfo";

export const isConnectedToInternet = () => {
    return new Promise((resolve, reject) => {
        NetInfo.fetch().then(state => {
            resolve(state.isConnected);
        }).catch(e => reject(e));
    })
};

答案 1 :(得分:0)

在移动软件中,最佳实践是始终尝试使用远程API,然后在没有互联网的情况下处理异常。 iOS和Android提供的可达性API并不总是准确的-它们需要轮询以确定连接性。因此,最好是应用程序始终尝试使用fetch,即使它认为互联网可能已关闭,以防设备自上次可访问性检查以来恢复了连接。

如果您希望对某些状态建模,以在应用程序认为其脱机时显示UI,则可以使用NetInfo.addEventListener()函数。我想也有一个React钩子。