react原生netinfo在无数据连接时返回true

问题描述 投票:0回答:1

我对

react-native-community/netinfo
包裹有疑问

我的

react-native-community/netinfo
版本是9.5.0,我的
react native
版本是0.70.7。

反应版本是18.1.0

我使用

isInternetReachable
来检测互联网可达性,问题是当我连接 Wi-Fi 时,但没有数据连接时,
isInternetReachable
仍然返回
true
。我该如何解决它?

我尝试了文档中找到的所有侦听器和所有可能的方法,但没有得到结果。

有人可以帮我弄清楚如何做到这一点吗?

reactjs react-native reachability react-native-community-netinfo
1个回答
0
投票

NetInfo 直接从本机端传输更新,无需任何计算。这有时会带来不良行为。

https://github.com/react-native-netinfo/react-native-netinfo?tab=readme-ov-file#addeventlistener

订阅连接信息。回调被调用 每当连接状态发生变化时,类型为 NetInfoState 的参数。 您的听众将很快收到最新信息 您订阅,然后进行任何后续更改。你 不应假设监听器以相同的方式被调用 设备或平台。

解决方案

每当网络状态发生变化时,Netinfo 最多可以对您执行 5 次以上的 ping 操作,对我来说有效的是使事件侦听器响应去抖动一秒钟,这样它就可以按预期工作。另外,该库不能很好地与 iOS Simulator 配合使用,您需要在真实设备上进行测试。

import { debounce } from 'lodash'
const DEBOUNCE_DURATION = 1000
...
React.useEffect(() => {
    const debouncedListener = debounce((response) => {
        console.log('netInfo response': response)
    }, DEBOUNCE_DURATION)
    const unsubscribe = netInfo.addEventListener((response) => {
        debouncedListener(response)
    })

    return () => {
        // cancel the debounced function when unsubscribing
        debouncedListener.cancel()
        // unsubscribe
        unsubscribe()
    }
}, [])

如果您想解决网络连接来自热点时的问题。

您不仅需要使用

isConnected
平,还需要使用
isInternetReachable
。如果这对您不起作用,您可以应用一个逻辑,每次 netInfo 返回 isConnected && isInternetReachable true 时,您可以集成 https://www.npmjs.com/package/react-native-ping 并执行双重操作在事件侦听器发出后检查

import { debounce } from 'lodash'
const DEBOUNCE_DURATION = 1000
...
React.useEffect(() => {
    const debouncedListener = debounce((response) => {
        console.log('netInfo response': response)
        // assuming that isConnected && isInternetReachable are both true.
        try {
            const ms = await Ping.start('114.114.114.114',{ 
            timeout: 1000 });
            // YOU HAVE INTERNET CONNECTION
        } catch (error) {
            // YOU ARE OFFLINE
        }
    }, DEBOUNCE_DURATION)
    const unsubscribe = netInfo.addEventListener((response) => {
        debouncedListener(response)
    })

    return () => {
        // cancel the debounced function when unsubscribing
        debouncedListener.cancel()
        // unsubscribe
        unsubscribe()
    }
}, [])
© www.soinside.com 2019 - 2024. All rights reserved.