【问题标题】:React Native - Store data in local DB/AsyncStorage with no Internet connection?React Native - 在没有 Internet 连接的情况下将数据存储在本地 DB/AsyncStorage 中?
【发布时间】:2020-03-21 05:52:55
【问题描述】:

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

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

【问题讨论】:

    标签: react-native react-native-android offline mobile-application asyncstorage


    【解决方案1】:

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

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

    【讨论】:

    • 当然我会尝试的。您是否在公共 git 中实现了上述场景??
    • 非常感谢!我会在我的应用程序中肯定会尝试这个。如果我卡在某个地方,我会在这里回复。
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 2018-03-05
    • 1970-01-01
    • 2020-08-07
    • 2017-09-09
    • 1970-01-01
    • 2021-08-13
    • 2021-10-24
    相关资源
    最近更新 更多