React-Native開發七 react-navigation之AsyncStorage資料儲存
阿新 • • 發佈:2018-11-01
1 前言
我們都知道,在Android和IOS中分別有不同的持久化資料方式,例如Android中的檔案,資料庫,SharePrefences等。AsyncStorage是一個簡單的key-value儲存系統,是RN官方推薦的。它儲存的都是String型別的資料,是一個RN中輕量級的資料持久化技術
2 AsyncStorage主要用法
export const AsyncStorage: AsyncStorageStatic;
export type AsyncStorage = AsyncStorageStatic;
/**
* AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage
* system that is global to the app. It should be used instead of LocalStorage.
*
* It is recommended that you use an abstraction on top of `AsyncStorage`
* instead of `AsyncStorage` directly for anything more than light usage since
* it operates globally.
*
* On iOS, `AsyncStorage` is backed by native code that stores small values in a
* serialized dictionary and larger values in separate files. On Android,
* `AsyncStorage` will use either [RocksDB](http://rocksdb.org/) or SQLite
* based on what is available.
*
* @see https://facebook.github.io/react-native/docs/asyncstorage.html#content
*/
export interface AsyncStorageStatic {
/**
* Fetches key and passes the result to callback, along with an Error if there is any.
*/
getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;
/**
* Sets value for key and calls callback on completion, along with an Error if there is any
*/
setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;
removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;
/**
* Merges existing value with input value, assuming they are stringified json. Returns a Promise object.
* Not supported by all native implementation
*/
mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;
/**
* Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this.
* Use removeItem or multiRemove to clear only your own keys instead.
*/
clear(callback?: (error?: Error) => void): Promise<void>;
/**
* Gets all keys known to the app, for all callers, libraries, etc
*/
getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise<string[]>;
/**
* multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet
*/
multiGet(
keys: string[],
callback?: (errors?: Error[], result?: [string, string][]) => void
): Promise<[string, string][]>;
/**
* multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet,
*
* multiSet([['k1', 'val1'], ['k2', 'val2']], cb);
*/
multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;
/**
* Delete all the keys in the keys array.
*/
multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise<void>;
/**
* Merges existing values with input values, assuming they are stringified json.
* Returns a Promise object.
*
* Not supported by all native implementations.
*/
multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;
}
可以看到AsyncStorage儲存的都是String-String型別,和Android中的SharePrefences很像,在js中如果需要儲存物件,需要使用JSON序列化進行儲存。好在js中物件的定義就是符合JSON物件的形式的,因此序列化起來非常方便。
3 AsyncStorage Demo例項
在使用AsyncStorage時,我們需要從react-native中匯入該元件,下面以常用的getItem,setItem,removeItem為例,來講解基本使用。先來看api介紹
/**
* Fetches key and passes the result to callback, along with an Error if there is any.
*/
getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;
/**
* Sets value for key and calls callback on completion, along with an Error if there is any
*/
setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;
removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;
getItem對應獲取資料,引數是傳入一個key,然後有一個回撥,如果是錯誤的話error不為null,否則讀取result
setItem對應儲存資料,需要傳輸key,資料以及錯誤的回撥
removeItem物件刪除資料,需要傳入key以及對應的錯誤的回撥。
下面看Demo原始碼
import React,{Component}from "react";
import {View,TouchableOpacity, Text, TextInput, AsyncStorage} from "react-native";
import Toast, {DURATION} from 'react-native-easy-toast'
const KEY = "key";
export default class AsyncStorageDemo extends Component{
constructor(props){
super(props);
}
render(){
return (
<View>
{/*賦值給AsyncStorageDemo.text變數*/}
<TextInput onChangeText={(text) => this.text=text}/>
<View style={{flexDirection:"row",justifyContent:"space-between", margin:10}}>
<TouchableOpacity onPress={() => this.onSave()}>
<Text>儲存</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.onRemove()}>
<Text>刪除</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.onFetch()}>
<Text>獲取</Text>
</TouchableOpacity>
</View>
<Toast ref={(toast) => this.toast = toast}/>
</View>
);
}
onSave(){
AsyncStorage.setItem(KEY,this.text,(error) => {
if (!error){
this.toast.show("儲存成功",DURATION.LENGTH_SHORT);
} else {
this.toast.show("儲存失敗",DURATION.LENGTH_SHORT);
}
})
}
onRemove(){
AsyncStorage.removeItem(KEY,(error) => {
if (!error){
this.toast.show("刪除成功",DURATION.LENGTH_SHORT);
} else {
this.toast.show("刪除失敗",DURATION.LENGTH_SHORT);
}
})
}
onFetch(){
AsyncStorage.getItem(KEY,(error,result) => {
if (!error){
if (result !== null && result !== ""){
this.toast.show("獲取成功:" + result,DURATION.LENGTH_SHORT);
} else {
this.toast.show("不存在" + result,DURATION.LENGTH_SHORT);
}
} else {
this.toast.show("獲取失敗",DURATION.LENGTH_SHORT);
}
})
}
}
程式碼還是挺簡單的,就不做過多講解了。下面看執行效果