反应本机状态不更新

时间:2019-02-26 12:35:58

标签: react-native

我的应用需要联网才能获取数据库。 开启WIFI并打开应用程序后一切正常,并在显示徽标几秒钟后导航至主页,但是当我的WIFI处于关闭状态且毫无疑问的打开应用程序无法获取数据时,但打开WIFI数据无法获取时,这意味着状态表明保存数据不会随着连接到互联网而更新,应再次关闭应用以进行获取...

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 />
 )    

}

}

和我检查互联网连接的组件是:

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>
)

} }

2 个答案:

答案 0 :(得分:1)

首先, 安装此npm软件包 [https://www.npmjs.com/package/react-native-offline][1] 它将提供两个组件, 1)NetworkProvider 2)NetworkConsumer

然后, 如下将整个应用包装到NetworkProvider中

<NetworkProvider>
 <App />
</NetworkProvider>

最后, 您可以按如下方式将子组件包装在NetworkConsumer中

<NetworkConsumer>
  {({ isConnected }) => (
    isConnected ? (
      <Button title="Download image" onPress={downloadImage} />
    ) : (
      <Text>Downloading images is disabled since you are offline</Text>
    )
  )}
</NetworkConsumer>

希望这能奏效...;-)

答案 1 :(得分:0)

首先,您需要监视网络的状态。可以使用NetInfo

下一步,当您连接到网络时,可能必须再次发送请求。