我对 React Native 还是有点陌生。我正在尝试检测用户的 Internet 连接状态并根据结果显示一个按钮。如果未检测到 Internet 连接,我想退出应用程序。我的完整代码如下。
import React from 'react'
import { Button, StyleSheet, Text, View } from 'react-native'
import { Actions } from 'react-native-router-flux'
import FlatContainer from './components/FlatContainer';
import NetInfo from "@react-native-community/netinfo";
const Welcome = () => {
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
var _connection = JSON.stringify(state.isConnected)
});
const goToHome = () => {
Actions.home()
}
return (
<View style={styles.page}>
<FlatContainer style={styles.container1}>
<Text>Welcome!</Text>
</FlatContainer>
<FlatContainer style={styles.container2}>
{_connection === "true" ? (
<View style={styles.button}>
<Button title='Button' color='blue' onPress={goToHome}/>
</View>
) : (
<View style={styles.button}>
<Button title='Exit' color='blue'/> //use 'BackHandler' here to exit?
</View>
)}
</FlatContainer>
<FlatContainer style={styles.container3}>
<Text>image</Text>
</FlatContainer>
</View>
)
}
const styles = StyleSheet.create({
page:{
flex:1,
paddingTop:50,
backgroundColor: 'black'
},
container1: {
backgroundColor: 'black',
height : 100
},
container2: {
backgroundColor: 'black',
height : 100
},
container3: {
backgroundColor: 'black',
height : 100
},
button:{
width:80,
height:40,
color: 'white',
backgroundColor: 'white'
}
});
export default Welcome
问题是,虽然“NetInfo”似乎可以正常工作以确定 Internet 连接状态,但似乎我无法将该信息传输到变量(“_connection”)。该变量用于确定要显示的按钮。“_connection”似乎无法识别。
此外,我相信我需要导入“BackHandler”模块来编写代码,以允许用户在按下正确的按钮后退出应用程序,但是我还没有编写该部分,因为我的代码由于无法识别的变量而崩溃。非常感谢任何建议。问候。
在其他人的一些输入和一些研究之后,我的代码如下,它看起来像这里写的那样有效:
const Welcome = () => {
const [isConnected, setIsConnected] = useState(false); //assume NO Internet connectivity...
const netInfo = useNetInfo();
useEffect(() => {
setIsConnected(netInfo.isConnected);
});
const goToHome = () => {
Actions.home()
}
const buttonToShowIfConnected = <Button title='Home' color='blue' onPress={goToHome}/>
const buttonToShowIfNotConnected = <Button title='Exit' color='blue' onPress={goToHome}/>
let conditionalButton = isConnected ? buttonToShowIfConnected : buttonToShowIfNotConnected
return (
<View style={styles.page}>
<FlatContainer style={styles.container1}>
<Text>Welcome</Text>
<Text>Type: {netInfo.type}</Text>
<Text>Is Connected? {netInfo.isConnected.toString()}</Text>
</FlatContainer>
<FlatContainer style={styles.container2}>
{conditionalButton}
</FlatContainer>
<FlatContainer style={styles.container3}>
<Text>image</Text>
</FlatContainer>
</View>
)
}
const styles = StyleSheet.create({
//stuff
}