react-native - React Native - 在没有 Internet 连接的情况下将数据存储在本地 DB/AsyncStorage 中?
问题描述
制作离线友好应用程序的最佳方法是什么,我的要求是无论互联网连接如何,都永远不要阻止用户提交数据。
当有连接时,直接将数据发布到在线服务器,当没有连接时,将数据存储在某种本地存储(可靠)中,直到再次建立连接,在这种情况下立即将数据发送到在线服务器。
解决方案
你可以使用这个库,我在我的多个项目中使用过
当应用未连接互联网时,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);
推荐阅读
- sql-server - 带有 SQL Server 的 Docker 无法使用 sqlcmd 将值插入数据库
- openedge - 如何从进度 4GL 上的内部程序持续调用外部程序?
- angular - 如何以角度反应形式保持价值?
- github - Azure Devops ci 管道无法构建 asp.net 核心项目,因为它位于 github repo 的子文件夹中
- regex - 正则表达式 - 最后一个时期和最后一个下划线之间的所有内容
- apache - htaccess 追加查询字符串
- javascript - 如何扩展剑道编辑器小部件?
- java - 如何强制 Hibernate 读取外部数据库更改
- html - 某些字段未保存在 django-models 中
- javascript - 没有初始状态的反应钩子