gpt4 book ai didi

reactjs - 当我关闭互联网连接时,它没有显示来自 NetInfo.isConnect 函数的错误值

转载 作者:行者123 更新时间:2023-12-04 02:44:36 24 4
gpt4 key购买 nike

当我从真实设备上关闭互联网连接时,它没有检测到我处于离线状态,但是当再次上线时,它会将值返回为 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')
}

到目前为止,我没有在这里提到 render()。

最佳答案

使用 React Native Community's NetInfo 因为 RN's version is deprecated .

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() {...}
}

关于reactjs - 当我关闭互联网连接时,它没有显示来自 NetInfo.isConnect 函数的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766348/

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