2

我正在尝试在客户端 React Native 应用程序中实现离线(尚未添加 - 但也是低连接)网络错误弹出消息。

这是我的完整视图代码:

import React, {useState, useEffect} from 'react';
import {Dimensions, View, Text} from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import * as Animatable from 'react-native-animatable';

export default function InternetCheck() {
  const APP_NAME = 'Security App';
  const [isConnected, setIsConnected] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    //Intial status

    NetInfo.fetch().then((state) => {
      
        setIsConnected(state.isInternetReachable);
    });

    //Internet connection listener
    NetInfo.addEventListener((state) => {
      console.warn('called');
      console.warn(state.isInternetReachable);

      setIsConnected(state.isInternetReachable);

    });
  }, []);

  return (
    <React.Fragment>
      {!isConnected && (
        <Animatable.View
          style={{
            backgroundColor: 'red',
            borderTopLeftRadius: 40,
            flexDirection: 'row',
            position: 'absolute',
            zIndex: 2,
            top: 30,
            width: Dimensions.get('window').width / 1.5,
            height: 40,
            alignItems: 'center',
            alignContent: 'center',
            alignSelf: 'center',
            borderRadius: 50,
          }}
          animation="fadeInDown">
          <View style={{flex: 2}}>
            <Text
              style={{
                color: '#fff',
                textAlign: 'center',
                alignSelf: 'center',
                fontWeight: '700',
              }}>
              * WARNING You are Currently OFFLINE - Please reconnect to use this apps features. 
            </Text>
          </View>
        </Animatable.View>
      )}
      {isConnected && (
        <Animatable.View
          style={{
            backgroundColor: 'green',
            borderTopLeftRadius: 40,
            flexDirection: 'row',
            position: 'absolute',
            zIndex: 2,
            top: 30,
            width: Dimensions.get('window').width / 1.5,
            height: 40,
            alignItems: 'center',
            alignContent: 'center',
            alignSelf: 'center',
            borderRadius: 50,
          }}
          animation="fadeOutUp"
          duration={5000}
          delay={2000}>
          <View style={{flex: 2}}>
            <Text
              style={{
                color: '#fff',
                textAlign: 'center',
                alignSelf: 'center',
                fontWeight: '700',
              }}>
              You're back online!
            </Text>
          </View>
        </Animatable.View>
      )}
    </React.Fragment>
  );
}

我的问题是断开模拟器网络时错误消息显示没有问题。控制台日志消息和动画消息都会出现。但是在恢复网络时,事件侦听器不会重新运行。因此isConnected状态永远不会返回到true,尽管连接已恢复。

任何人都可以建议我哪里出错或建议替代方法。

4

1 回答 1

4

iOS 模拟器无法重新连接存在一个已知问题(正在故障排除中),因此如果您在 iOS 模拟器上进行测试,请知道它不会触发,您需要试用物理设备。但如果这发生在 android 模拟器上,那可能是其他事情。

于 2021-09-29T14:35:55.577 回答