RN使用AsyncStore將數(shù)據(jù)存儲(chǔ)到本地溪猿,AsyncStorage是一個(gè)基于key-value鍵值對(duì)的異步持久化存儲(chǔ)系統(tǒng),對(duì)于應(yīng)用來說其存儲(chǔ)的內(nèi)容全局生效纫塌。
AsyncStorage使用異步Promise模式存儲(chǔ)數(shù)據(jù)诊县,例如調(diào)用存儲(chǔ)方法存儲(chǔ)一個(gè)字符串setItem('I_AM_KEY','i_am_value')
,setItem會(huì)異步執(zhí)行护戳,等setItem執(zhí)行完成后會(huì)返回一個(gè)Promise對(duì)象翎冲。
'use strict';
import React,{AsyncStorage,Component,TouchableOpacity,View,Text,AppRegistry} from 'react-native';
// 數(shù)據(jù)對(duì)應(yīng)的key
var STORAGE_KEY = 'I_AM_KEY';
class Demo extends Component{
// 獲取
async _get() {
console.log('Demo._get()');
try {// try catch 捕獲異步執(zhí)行的異常
var value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null){
console.log('_get() success: ' ,value);
} else {
console.log('_get() no data');
}
} catch (error) {
console.log('_get() error: ',error.message);
}
}
// 保存
async _save(value) {
console.log('Demo._save()');
try {
await AsyncStorage.setItem(STORAGE_KEY, value);
console.log('_save success: ',value);
} catch (error) {
console.log('_save error: ',error.message);
}
}
// 刪除
async _remove() {
console.log('Demo._remove()');
try {
await AsyncStorage.removeItem(STORAGE_KEY);
console.log('_remove() success');
} catch (error) {
console.log('_remove() error: ', error.message);
}
}
render(){
return(
<View style={{flexDirection:'column',flex:1,marginTop:50,}}>
<TouchableOpacity style={{padding:10,flex:1,flexDirection:'row',}} onPress={()=>this._save('haha').then(()=>console.log('you can do something here when the setItem is starting')).done(()=>console.log('you can do something here when the setItem is done'));}>
<Text style={{fontSize:16,color:'#333333'}}>保存數(shù)據(jù)</Text>
</TouchableOpacity>
<TouchableOpacity style={{padding:10,flex:1,flexDirection:'row',}} onPress={()=>this._get().done()}>
<Text style={{fontSize:16,color:'#333333'}}>獲取數(shù)據(jù)</Text>
</TouchableOpacity>
<TouchableOpacity style={{padding:10,flex:1,flexDirection:'row',}} onPress={()=>this._remove()}>
<Text style={{fontSize:16,color:'#333333'}}>刪除數(shù)據(jù)</Text>
</TouchableOpacity>
</View>);
}
}
AppRegistry.registerComponent('Demo', () => Demo);
代碼很簡(jiǎn)單媳荒,點(diǎn)擊三個(gè)按鈕就可以看到console控制臺(tái)的輸出數(shù)據(jù)抗悍。
ES6中promise提供了幾個(gè)回調(diào)方法then,done钳枕,finally缴渊,如下所示:
this._save('haha').then(()=>console.log('you can do something here when the setItem is starting')).done(()=>console.log('you can do something here when the setItem is done'));
then()方法會(huì)在setItem開始執(zhí)行后執(zhí)行
done()方法會(huì)在setItem執(zhí)行完成后調(diào)用,done
都會(huì)捕捉到任何可能出現(xiàn)的錯(cuò)誤鱼炒,并向全局拋出
finally則是回調(diào)鏈執(zhí)行的最后一個(gè)方法
AsyncStore全部方法列表參請(qǐng)參考官方文檔衔沼,或者在你的工程項(xiàng)目中搜索AsyncStore.js查看源碼。