本地儲存
選擇本地儲存資料庫時,最好與伺服端的資料庫搭配。 SQL搭配SQLite。mongoDB搭配Realm。 純手機應用(不用後端程式API)的資料庫,應該是搭配firebase。
AsyncStorage
類似cookie的用法,用key-value方式儲存。
全域,只能儲存字串(可自訂分隔符號儲存成陣列)。
無查詢功能。
設定:setItem(key,value)
讀取:getItem(key)
移除:removeItem(key)
SQLite
用npm安裝後才可使用
用SQL語法操作CRUD
效能和穩定性較差
Realm
JSON格式儲存
物件內的資料有查詢語法
物件間可設定關聯
官網的說明清楚易懂,開發前應先閱讀一遍
安裝使用
//安裝
npm install realm --save
//與專案連結
react-native link realm
書本範例
//home.js
//(省略)
import Realm from 'realm';
//(省略)
constructor(props) {
super(props);
this.state = {
//(省略)
//實體化realm並直接定義model
realm: new Realm({
schema: [
//其中一個realm model(物件)
{
//realm內model名稱(似table)
name: 'Product',
// 定義此物件的屬性
properties: {
id: 'int',
title: 'string',
subTitle: 'string',
image: 'string'
}
}
]
})
}
}
//從本地資料庫realm取值
_queryProducts = () => {
return this.state.realm.objects('Product');
}
//儲存資料到本地資料庫realm
_saveProducts = (products) => {
//write是寫入資料庫
this.state.realm.write(() => {
for (const i = 0; i < products.length; i++) {
//每筆資料
const product = products[i];
//create是新增資料到model(物件)
this.state.realm.create('Product', {
id: parseInt(product.id),
title: product.title,
subTitle: product.subTitle,
image: product.image
});
}
});
}
官網範例1:使用realm資料庫儲存及取值
const Realm = require('realm');
// 定義models和它的properties(之後要新增時必要)
// 類似table及欄位的定義
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: 'Car[]',
picture: 'data?' // optional property
}
};
//開啟資料庫內的models(promise結構)
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
// 將建立的物件寫入資料庫
realm.write(() => {
//新增資料到CarSchema內
const myCar = realm.create('Car', {
make: 'Honda',
model: 'Civic',
miles: 1000,
});
// Update a property value
myCar.miles += 20;
});
// 查詢Car內的資料,並過濾設定miles>1000
const cars = realm.objects('Car').filtered('miles > 1000');
// 查詢結果的筆數
cars.length // => 1
// 新增第二筆資料
realm.write(() => {
const myCar = realm.create('Car', {
make: 'Ford',
model: 'Focus',
miles: 2000,
});
});
// 查詢結果的筆數
cars.length // => 2
})
.catch(error => {
console.log(error);
});
官網範例2:在react native使用realm的時機
const Realm = require('realm');
class <project-name> extends Component {
constructor(props) {
super(props);
//預設realm為null
this.state = { realm: null };
}
//render前開啟資料庫,並宣告schema物件屬性(新增時必要)
//若有初始值可先賦予
componentWillMount() {
Realm.open({
schema: [{name: 'Dog', properties: {name: 'string'}}]
}).then(realm => {
realm.write(() => {
realm.create('Dog', {name: 'Rex'});
});
this.setState({ realm });
});
}
render() {
const info = this.state.realm
? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length
: 'Loading...';
return (
<View style={styles.container}>
<Text style={styles.welcome}>
{info}
</Text>
</View>
);
}
}
Last updated