React Native获取及监听网络状态
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Platform } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
const App = () => {
const [connectionInfo, setConnectionInfo] = useState({ type: '', isConnected: false });
useEffect(() => {
const unsubscribe = NetInfo.addEventListener((state) => {
setConnectionInfo(state);
});
// 组件卸载时移除监听器
return () => unsubscribe();
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>网络状态: {JSON.stringify(connectionInfo)}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
textAlign: 'center',
margin: 10,
},
});
export default App;
这段代码使用React Native和@react-native-community/netinfo
库来获取并监听网络状态。它使用了React的hook useEffect
来设置网络监听器,并使用 useState
来保存网络状态。当网络状态发生变化时,会更新UI显示最新的网络信息。
评论已关闭