vic*_*hri 3 networking reactjs react-native
当我从真实设备关闭互联网连接时,它没有检测到我处于离线状态,但是当再次上线时,它会将值返回为 true。
import React from 'react';
import {
SafeAreaView,
StyleSheet,
View,
Text,
StatusBar,
Image,
TouchableOpacity,
FlatList,
NetInfo
} from 'react-native';
export default class App extends React.Component {
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange',
this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange',
this.handleConnectivityChange);
}
handleConnectivityChange = (isConnected) => {
console.log(isConnected ? 'connected':'not connected')
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我没有在这里提到 render()。
使用React Native Community 的,NetInfo因为RN 的版本已弃用。
RNC 版本仅在添加侦听器时接受回调。
它应该是:
import NetInfo from "@react-native-community/netinfo";
export default class App extends React.Component {
constructor(props) {
super(props)
this.unsubscribe = null
}
componentDidMount() {
this.unsubscribe = NetInfo.addEventListener(
this.handleConnectivityChange
);
}
componentWillUnmount() {
this.unsubscribe();
}
handleConnectivityChange = (state) => {
console.log(state.isConnected ? 'connected': 'not connected')
}
render() {...}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |