gpt4 book ai didi

reactjs - React Native - 网络重新连接时不触发 NetInfo.addEventListener

转载 作者:行者123 更新时间:2023-12-02 18:31:29 26 4
gpt4 key购买 nike

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

这是我的完整 View 代码:

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,尽管已恢复连接。

任何人都可以告诉我哪里出了问题或建议替代方法吗。

最佳答案

iOS 模拟器无法重新连接 (under troubleshooting) 是一个已知问题,因此如果您在 iOS 模拟器上进行测试,请知道它不会触发,您需要尝试使用物理设备。但是,如果这发生在 Android 模拟器上,则可能是其他原因。

关于reactjs - React Native - 网络重新连接时不触发 NetInfo.addEventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69378071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com