非常感谢这些答案,但这里是一个完整的例子,使用useNetInfo
React Hook 触发当状态将要改变时,使用Alert
来通知用户,并向用户显示一些文本的View
。
import { useNetInfo, NetInfoState } from "@react-native-community/netinfo";
import {
Alert,
StyleSheet,
Text,
View,
} from "react-native";
...
const internetState: NetInfoState = useNetInfo();
...
useEffect(() => {
if (internetState.isConnected === false) {
Alert.alert(
"No Internet! ❌",
"Sorry, we need an Internet connection for MY_APP to run correctly.",
[{ text: "Okay" }]
);
}
}, [internetState.isConnected]);
...
if (internetState.isConnected === false) {
return (
<View style={styles.centered}>
<Text style={styles.title}>
Please turn on the Internet to use MY_APP.
</Text>
</View>
);
}
...
const styles = StyleSheet.create({
centered: {
alignItems: "center",
flex: 1,
justifyContent: "center",
},
title: {
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
},
});
PS. 我没有把它包含在 App.tsx
或 navigation/index.tsx
中,以避免代码重复。接下来尝试,我已将逻辑包含在每个 screen
中。对于 App.tsx
或 navigation/index.tsx
的情况,当互联网恢复时,用户将被重定向到应用程序的起始 screen
,这不是我想要的。我希望,当有网络且恢复时,用户回到他们离开的那个屏幕。使用多个屏幕中的逻辑时,会触发多个 alerts
:( 最后,我已将与 Alert
相关的逻辑包含在 App.tsx
中,而在每个 screen
中包含显示无互联网信息的 View
。 Alert
只弹出一次,但最好也避免 View
的代码重复。如果您知道如何从代码库的一个位置执行此操作,请随时发布更新。非常感谢!