在 class 中使用 @react-native-community/netinfo 可能吗?

Using @react-native-community/netinfo in a class, possible?

我正在尝试向我的应用程序添加一个功能,以添加一个视图,向用户指示他已断开与 Internet 网络的连接。

所以我去了@react-native-community/netinfo 进行设置,但我很快发现自己遇到了使用钩子的困难和相关错误:“Invalid hook call. Hooks can only be called inside of the body of a function component".

那么如何在基于class的应用程序上集成@react-native-community/netinfo?

我想在检测到连接状态更改时更改应用程序的状态,以显示或不显示指示断开连接状态的视图。

非常感谢您的帮助!

这是我用于测试的:

库中有一个开箱即用的挂钩,称为 useNetInfo(),您可以像这样使用它:

编辑:

您可以阅读 以将此挂钩用于基于 class 的应用程序。这类似于 netInfo.

Example from git, react-native-community

import {useNetInfo} from "@react-native-community/netinfo";

const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

编辑 2:

完整示例:

import React from 'react'
import { SafeAreaView, Text } from 'react-native'
import { useNetInfo } from '@react-native-community/netinfo'

export default class Home extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            netInfo: undefined
        }
    }

    setNetInfo = netInfo => {
        this.setState({netInfo})
    }

    render () {

        return (
            <SafeAreaView>
                <SetNetInfo setNetInfo={this.setNetInfo} />
                <Text>Hello world</Text>
            </SafeAreaView>
        )
    }

}

const SetNetInfo = ({ setNetInfo }) => {
    const netInfo = useNetInfo()

    React.useEffect(() => {
        setNetInfo(netInfo)
    },[netInfo])

    return null
}

我猜(根据错误消息)您在 class 本身中声明的侦听器是错误的。

只需将侦听器声明移至 componentDidMount 挂钩并在 componentWillUnmount 挂钩中取消订阅,它应该会按您预期的那样工作。

如果您需要完整示例,请发表评论,我会提供给您。干杯