gpt4 book ai didi

reactjs - 为什么在没有 Internet 的情况下启动应用程序时没有正确触发 React Native 的 NetInfo?

转载 作者:搜寻专家 更新时间:2023-10-30 21:47:22 25 4
gpt4 key购买 nike

我有一个组件来跟踪设备的互联网连接,并在没有连接时显示一个红色的小横幅。一般来说,它工作正常:当您在应用程序中切换互联网时,横幅会出现并消失。

但是,如果您在没有互联网的情况下启动应用,它不会显示横幅。一旦您打开互联网,它将从此正常工作。


这是组件,OfflineNotice.tsx:

import * as React from 'react';
import { NetInfo, StyleSheet, Text, View } from 'react-native';

interface State {
isConnected: boolean;
}

export class OfflineNotice extends React.Component<any, State> {
public state = {
isConnected: true,
};

public handleConnectivityChange = (isConnected: boolean) => {
if (isConnected !== this.state.isConnected) {
console.log('isConnected', isConnected);
this.setState({ isConnected });
}
};

public componentDidMount() {
NetInfo.isConnected.addEventListener(
'connectionChange',
this.handleConnectivityChange
);
}

public componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'connectionChange',
this.handleConnectivityChange
);
}

public render() {
if (!this.state.isConnected) {
return (
<View style={styles.container}>
<Text style={styles.offlineText}>
No Internet Connection
</Text>
</View>
);
}
return null;
}
}

最佳答案

作为JRK他在上面的评论中如此迅速地指出,解决方案很简单。连接变化触发事件,当你在没有互联网的情况下启动应用程序时,没有连接变化。

如果你initialise isConnected in state as false,当连接启动时事件将被触发.

最好的方法是在构造函数中:

constructor(props) {
super(props);

NetInfo.isConnected.fetch().then(isConnected => {
this.setState({isConnected});
});
}

如果你不这样做,而只是在 this.state 中将 isConnected 设置为 false 并在 中添加事件监听器code>componentDidMount,在Android上无法正常运行。上述 Prop 来自 a comment 的 Terry Bazi到有关此主题的 Medium 文章。

您可以在 NetInfo 上的 React Native 文档中的示例中了解更多信息,尤其是关于 isConnected 属性的最后部分:https://facebook.github.io/react-native/docs/netinfo#properties-1

关于reactjs - 为什么在没有 Internet 的情况下启动应用程序时没有正确触发 React Native 的 NetInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52596923/

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