这真的很难确定设备是否有互联网
stackoverflow.com/a/189443/7602110,仅通过失败的XHR请求就可以说你有互联网,但这可靠吗?您想要与一些可靠的网站进行检查,如
google.com。我已经想出了一个解决方法,但我实际上不建议这样做,这取决于您。
您可以使用React Native本身的Linking.canOpenUrl()
方法,它将返回一个Promise对象。当确定给定的URL是否可以处理时,该承诺被解决,并且第一个参数是它是否可以打开。
然后添加一个请求,如果响应状态为200
,则应该具有互联网。
![](https://istack.dev59.com/2AoFS.gif)
import React, { Component } from 'react';
import { Button, Text, View, StyleSheet, Linking } from 'react-native';
export default class App extends Component {
state = {
connection: false,
url: 'https://google.com',
};
checkInternt = () => {
Linking.canOpenURL(this.state.url).then(connection => {
if (!connection) {
this.setState({ connection: false });
} else {
fetch(this.state.url).then(res =>
this.setState({ connection: res.status !== 200 ? false : true })
);
}
});
};
componentDidMount() {
this.checkInternt();
}
handlePress = () => {
this.setState({
url:
this.state.url === 'https://google.com'
? 'http://someweirdurlthatdoesntwork.com'
: 'https://google.com',
});
this.checkInternt();
};
render() {
return (
<View style={styles.container}>
<Text>
Connection:
<Text style={{ color: this.state.connection ? 'green' : 'red' }}>
{` ${this.state.connection}`}
</Text>
</Text>
<Text>{this.state.url.replace(/\https?:\/\//g, '')}</Text>
<Button onPress={this.handlePress} title="Change server url" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
});
请检查小吃: snack.expo.io/@abranhe/check-internet
react-native link
。https://docs.expo.io/versions/latest/introduction/faq/#what-is-the-difference-between-expo-and - Dan B.