我的应用需要互联网以获取数据库。当WiFi打开并打开应用程序时,一切都很好,并且在Show徽标之后进行了第二次导航到主页,但是当我的wifi关闭并且打开应用程序无疑是无法获取数据时指出保存数据而不是与连接到Internet更新的数据,应再次关闭应用程序以获取...
import React, {Component} from 'react';
import {StyleSheet, View, Animated, StatusBar} from 'react-native';
import { Spinner } from 'native-base';
import Network from './Network'
const SuperUrl = 'http://site.domain'
export default class Intro extends Component {
constructor(){
super();
this.state={
isLoading: true,
dataSource: null,
}
}
componentDidMount()
{
return fetch(SuperUrl+'/check')
.then((response)=> response.json())
.then((responseJson)=>this.setState({
isLoading:false,
dataSource: responseJson.app_update
}));
}
render() {
var appStatus = this.state.dataSource;
if(this.state.isLoading===false && appStatus===0)
{
setTimeout(() => {
this.props.navigation.replace('test')
}, 2500);
}
return (
<View>...Logo Content...</View>
<Network />
)
}
}
和我检查Internet Connect的组件是:
import React, { Component } from 'react'
import { NetInfo, View } from 'react-native'
import {Root, Toast} from 'native-base'
export default class Network extends Component {
constructor(){
super();
this.state={connection: null}
}
componentWillMount(){
NetInfo.isConnected.addEventListener('connectionChange',this.handleconnectionChange);
}
componentWillUnmount(){
NetInfo.isConnected.removeEventListener('connectionChange',this.handleconnectionChange);
}
handleconnectionChange= (isConnected) => {this.setState({connection:isConnected})}
render() {
return (
<View style={{flex:1,}}>
<Root>
{(this.state.connection!=null && this.state.connection==false)?
Toast.show({
text: "at first please connect to internet.",
duration: 0,
type: 'danger'
})
:
null
}
</Root>
<Root>
{(this.state.connection!=null && this.state.connection==true)?
Toast.hide()
:
null
}
</Root>
</View>
)
}}
首先,安装此NPM软件包[https://www.npmjs.com/package/reaeact-native-offline * 1]它将提供两个组件,1)NetworkProvider2)NetworkConsumer
然后,将您的整个应用程序包装在NetworkProvider中,如下所示
<NetworkProvider>
<App />
</NetworkProvider>
,最后,您可以按照以下方式将子组件包装在网络库中
<NetworkConsumer>
{({ isConnected }) => (
isConnected ? (
<Button title="Download image" onPress={downloadImage} />
) : (
<Text>Downloading images is disabled since you are offline</Text>
)
)}
</NetworkConsumer>
希望这有效...; - )
首先,您需要监视网络的状态。这可以使用Netinfo完成。
接下来,您可能必须在连接到网络时再次发送请求。