在React Native应用中存储持久数据的选项有哪些
在创建React Native应用时,有几种方式可以存储或持久化数据。每种存储方法都有自己的优点。在本文中,我们将讨论在React Native应用中持久化数据的所有流行方法。
在讨论持久化数据的方法之前,您应该具备JavaScript和React/React Native的基本知识。您应该了解如何在React Native应用中使用库和配置来持久化数据。
先决条件:
- 基本的JavaScript库知识
- React Native应用的基础知识
React Native中持久化数据的方法:
React Native提供了几种持久化数据的方法。在这里,我们讨论最流行的方法。有些方法是内置的库,您需要安装和使用它们,而其他方法是外部插件。以下方法是在React Native中持久化数据的流行方法。
1. AsyncStorage: 它是在React Native应用中持久化数据的官方方法。这是由React Native在其文档中提供的。基本上,AsyncStorage类似于存储类,并使用键值对作为参数来持久化数据。
但是AsyncStorage类是异步的;设备上的数据存储不是永久的也不是加密的,因此,使用该方法时,您将需要提供自己的备份和同步类。所以,如果您的应用程序处理大量数据,则不要使用AsyncStorage方法。
如何使用AsyncStorage: 按照以下步骤操作:
步骤1:导入AsyncStorage库:
此代码行从React Native应用程序包中导入AsyncStorage类库。
import { AsyncStorage } from "react-native";
步骤2:持久化数据:
这将创建一个异步保存数据的函数。
_storeData = async () => {
try {
await AsyncStorage.setItem('name', 'Tom');
} catch (error) {
// Error saving data
}
}
步骤3:获取持久化数据:
它以异步方式获取数据
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('name');
if (value !== null) {
// Our data is fetched successfully
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
2. React Native SQLite 2: 这不是一个React库的功能,因此您可以在React Native应用程序中外部安装此插件。该插件由WebSQL API提供,用于持久化数据。它使用查询操作将数据持久化到我们的数据库中。
它支持所有操作系统,如Windows、iOS和Android。该插件可以被视为react-native-sqlite-storage库的替代品。
如何使用React Native SQLite 2: 按照以下步骤进行:
步骤1:安装 React Native SQLite 2:
$ npm install react-native-sqlite-2 --save
步骤2: 链接到库依赖项:
$ react-native link react-native-sqlite-2
步骤3: 导入库:
import SQLite from 'react-native-sqlite-2';
步骤4: 打开数据库文件:
const db = SQLite.openDatabase('test.db', '1.0', '', 1);
步骤5: 创建一个事务函数来执行SQL语句:
db.transaction(function (txn) {
// 如果存在则删除表
txn.executeSql('DROP TABLE IF EXISTS Users', []);
// 创建表并定义列的属性
txn.executeSql('CREATE TABLE IF NOT EXISTS Users(user_id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(30))', []);
// 插入一条记录
txn.executeSql('INSERT INTO Users (name) VALUES (:name)', ['tom']);
// 再插入一条记录
txn.executeSql('INSERT INTO Users (name) VALUES (:name)', ['jerry']);
// 查询所有插入的记录,并在控制台上打印出来
txn.executeSql('SELECT * FROM `users`', [], function (tx, res) {
for (let i = 0; i < res.rows.length; ++i) {
console.log('item:', res.rows.item(i));
}
});
});
3. Realm: 它专门为移动设备设计。它是基于对象的数据库,因此比SQLite快10倍。由于支持关系数据库系统,因此使用起来很简单。它将数据公开为对象。
Realm可以与服务器端数据集合连接,以允许离线与云端/服务器数据集合保持一致的信息同步。如果您的应用程序将处理大量数据,则Realm是一个很好的选择。
如何使用Realm: 按照以下步骤进行:
步骤1: 在React Native中安装Realm:
$ npm install realm --save
步骤2: 链接到库依赖项:
$ react-native link realm
步骤3: 导入库:
const Realm = require('realm');
步骤4: 将领域状态初始化为null:
constructor(props) {
super(props);
this.state = { realm: null };
}
步骤5: 持续坚持数据:
componentWillMount() {
// Open a Realm Schema
Realm.open({
schema: [{ name: 'Dog', properties: { name: 'string' } }]
}).then(realm => {
// Write a record into the realm schema
realm.write(() => {
realm.create('Dog', { name: 'Rex' });
});
// Update the realm state
this.setState({ realm });
});
}
步骤6: 获取和渲染:
render() {
const info = this.state.realm ?
'Number of dogs in this Realm: ' +
this.state.realm.objects('Dog').length :
'Loading...';
return (
<View style={styles.container}></View>
<Text style={styles.welcome}>
{info}
</Text>
</View >
);
}
步骤7: 将获取和渲染合并为一个组件:
// import the library
const Realm = require('realm');
class RealmDb extends Component {
//initiate the realm state to null
constructor(props) {
super(props);
this.state = { realm: null };
}
// persist data and write it into the realm state
// as soon as the component mounts
componentWillMount() {
// Open a Realm Schema
Realm.open({
schema: [{ name: 'Dog', properties: { name: 'string' } }]
}).then(realm => {
// Write a record into the realm schema
realm.write(() => {
realm.create('Dog', { name: 'Rex' });
});
// Update the realm state
this.setState({ realm });
});
}
// render a Text component with the value
render() {
const info = this.state.realm ?
'Number of dogs in this Realm: ' +
this.state.realm.objects('Dog').length :
'Loading...';
return (
<View style={styles.container}></View>
<Text style={styles.welcome}>
{info}
</Text>
</View >
);
}
}
4. React Native本地MongoDB: MongoDB 是一种跨平台、面向文档的服务器端数据库,提供高性能、可用性和易扩展性。MongoDB基于文档的概念工作。
MongoDB是一个开源的、面向文档的服务器端数据库,用于可扩展和复杂应用和大数据。它使用键值存储和关系型数据库将数据存储为JSON文档中的对象。
MongoDB允许服务器和应用之间进行平滑的通信。当您在应用中处理大量数据时,它是一个正确的选择。
如何使用MongoDB: 按照以下步骤操作:
步骤1: 在您的React Native应用程序中安装MongoDB:
$ npm install react-native-local-mongodb --save
步骤2: 创建数据存储:
var Datastore = require('react-native-local-mongodb'),
db = new Datastore({ filename: 'asyncStorageKey', autoload: true });
步骤3: 将其插入到您的数据库中:
db.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) {
// Two documents were inserted in the database
});
步骤4: 寻找一份文档:
db.find({ system: 'solar' }, function (err, docs) {
// docs is an array containing documents Mars, Earth, Jupiter
// If no document is found, docs is equal to []
});
步骤5: 更新一个文档:
db.update({ planet: 'Jupiter' }, {
planet: 'Neptune}, {}, function (err, numReplaced) {
// numReplaced = 1
// The doc has been replaced
// by { _id: 'id3', planet: 'Neptune' }
// Note that the _id is kept unchanged,
// and the document has been replaced
});
步骤6: 移除文档:
db.remove({ _id: 'id2' }, {}, function (err, numRemoved) {
// numRemoved = 1
});
Indexing:
db.ensureIndex({ fieldName: 'somefield' }, function (err) {
// If there was an error, err is not null
});
结论: 在本文中,我们讨论了在React Native应用程序中持久化数据的所有流行方式。选择使用哪种数据持久化方法取决于您要处理的数据类型和数量。
我们已经看到了四种在React Native中持久化数据的方法,每种方法都有其自身的优势。AsyncStorage处理小规模存储和序列化数据,而SQLite、Realm和MongoDB处理大规模存储数据。
根据应用程序的复杂性,您可以使用以上列表中的一种方法。
极客教程