我正在尝试向我的应用程序添加一个功能,以向用户添加一个视图,该视图指示用户与互联网断开连接。
所以我去了@ react-native-community / netinfo进行设置,但是我很快发现自己面临使用钩子的困难以及相关的错误:“ Invalid hook call. Hooks can only be called inside of the body of a function component
”
那么如何在基于类的应用程序上集成@ react-native-community / netinfo?
我想在检测到连接状态更改时更改应用程序的状态,以显示或不显示指示断开状态的视图。
我们将非常感谢您的帮助!
这是我用于测试的内容:
答案 0 :(得分:1)
我猜(根据错误消息),您在类本身中声明了侦听器,这是错误的。
只需将侦听器声明移至componentDidMount
钩子并在componentWillUnmount
钩子中取消订阅,它便会按预期工作。
如果您需要完整的示例,请留下评论,我会提供给您。干杯
答案 1 :(得分:0)
库中有一个可以立即使用的钩子,称为useNetInfo(),您可以像这样使用它:
编辑:
您可以阅读this answer以便将此钩子用于基于类的应用程序。这类似于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
}