RN使用AsyncStore將數(shù)據(jù)存儲(chǔ)到本地,AsyncStorage是一個(gè)基于key-value鍵值對的異步持久化存儲(chǔ)系統(tǒng),對于應(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對象疏橄。
舉個(gè)例子:
'use strict';
import React,{AsyncStorage,Component,TouchableOpacity,View,Text,AppRegistry} from 'react-native';
// 數(shù)據(jù)對應(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);
代碼很簡單略就,點(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全部方法列表參請參考官方文檔彰导,或者在你的工程項(xiàng)目中搜索AsyncStore.js查看源碼。
參考資料:
官方AsyncStore
React Native Storage第三方組件
Promise的回調(diào)方法
JavaScript ES7 中使用 async/await 解決回調(diào)函數(shù)嵌套問題