首页 > 解决方案 > 处理 React Native 上的 Internet 连接丢失

问题描述

我制作了一个 React Native App,它使用 Android 上的前台服务扫描 BLE 设备。我遇到的问题是处理互联网连接的丢失。一旦互联网可用,当互联网不可用时添加到队列中的待处理操作将不会执行。

一旦检测到信标,我就会使用 NativeModules 向 React Native 发送一个事件,收到该事件后,我会检查互联网是否可用。如果不是,则将其存储在队列中。

    const didEnterRegion = async (store, beacons) => {
      const { isConnected } = store.getState().connection;

      if (isConnected) {
        store.dispatch({
          type: REQUEST_CHECKIN,
          payload: beacons,
        });
      } else {
        NativeModules.BeaconFinder.sendNotification(
          'Looks like you entered a venue, but the internet is not reachable.',
          beacons.uuid.toString(),
        );
        store.dispatch({
          type: ADD_ACTION_TO_QUEUE,
          name: REQUEST_CHECKIN,
          payload: beacons,
        });
      }
    };

在 App.js 中,我不断检查互联网连接。如果可用,我将执行队列中的所有操作。

    export default class App extends Component {
      componentDidMount() {
        const unsubscribe = NetInfo.addEventListener(state => {
          this._handleConnectionChange(state.isInternetReachable);
        });
      }

      componentWillUnmount() {
        //unsubscribe();
      }

      _handleConnectionChange = isConnected => {
        if (isConnected && _.size(store.getState().connection.actionQueue) > 0) {
          let queue = store.getState().connection.actionQueue;

          _.map(queue, action => {
            console.log(action);
            store.dispatch({
              type: action.name,
              payload: action.payload
            });
          });
        }
        store.dispatch({
          type: CHANGE_CONNECTION_STATUS,
          isConnected
        });
      };
      render...
}

这在应用程序处于前台时有效,但是当应用程序从任务切换器中终止时,代码会随机执行,即有时有效,有时无效。

标签: javascriptandroidreact-nativereduxaltbeacon

解决方案


推荐阅读