首页 > 解决方案 > React Native - 在没有 Internet 连接的情况下将数据存储在本地 DB/AsyncStorage 中?

问题描述

制作离线友好应用程序的最佳方法是什么,我的要求是无论互联网连接如何,都永远不要阻止用户提交数据。

当有连接时,直接将数据发布到在线服务器,当没有连接时,将数据存储在某种本地存储(可靠)中,直到再次建立连接,在这种情况下立即将数据发送到在线服务器。

标签: react-nativereact-native-androidofflinemobile-applicationasyncstorage

解决方案


你可以使用这个库,我在我的多个项目中使用过

当应用未连接互联网时,react-native-netinfo将向您返回回调

您可以在那里执行和处理进一步的操作 *

A small example
now you'll get the value in redux if your device is connected or not

*

并记住它在真实设备上的模拟器测试中效果不佳

import React from 'react';
// import NetInfo from "@react-native-community/netinfo";
import { View, Text, Dimensions, StyleSheet ,NetInfo} from 'react-native';
import {toggleNetworkState} from '../../actions/list';
import { connect } from 'react-redux';
const { width } = Dimensions.get('window');

function MiniOfflineSign() {
  return (
    <View style={styles.offlineContainer}>
      <Text style={styles.offlineText}>No Internet Connection</Text>
    </View>
  );
}

class OfflineNotice extends React.Component {
  state = {
    isConnected: false
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    // NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => {
    this.setState({
        isConnected: isConnected
    })
    this.props.toggleNetworkState(isConnected);
  };

  

  render() {
    if (!this.props.state.list.isNetwork) {
      return <MiniOfflineSign />;
    }
    return null;
  }
}

const styles = StyleSheet.create({
  offlineContainer: {
    backgroundColor: '#b52424',
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    width,
    position: 'absolute',
    top: 64,
    zIndex:1,
  },
  offlineText: { color: '#fff' }
});


const mapStateToProps = state => ({
    state
    });

export default connect(mapStateToProps, {toggleNetworkState})(OfflineNotice);


推荐阅读