RN使用AsyncStore将数据存储到本地,AsyncStorage是一个基于key-value键值对的异步持久化存储系统,对于应用来说其存储的内容全局生效。
AsyncStorage使用异步Promise模式存储数据,例如调用存储方法存储一个字符串setItem('I_AM_KEY','i_am_value')
,setItem会异步执行,等setItem执行完成后会返回一个Promise对象。
'use strict';
import React,{AsyncStorage,Component,TouchableOpacity,View,Text,AppRegistry} from 'react-native';
// 数据对应的key
var STORAGE_KEY = 'I_AM_KEY';
class Demo extends Component{
// 获取
async _get() {
console.log('Demo._get()');
try {// try catch 捕获异步执行的异常
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'}}>保存数据</Text>
</TouchableOpacity>
<TouchableOpacity style={{padding:10,flex:1,flexDirection:'row',}} onPress={()=>this._get().done()}>
<Text style={{fontSize:16,color:'#333333'}}>获取数据</Text>
</TouchableOpacity>
<TouchableOpacity style={{padding:10,flex:1,flexDirection:'row',}} onPress={()=>this._remove()}>
<Text style={{fontSize:16,color:'#333333'}}>删除数据</Text>
</TouchableOpacity>
</View>);
}
}
AppRegistry.registerComponent('Demo', () => Demo);
代码很简单,点击三个按钮就可以看到console控制台的输出数据。
ES6中promise提供了几个回调方法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()方法会在setItem开始执行后执行
done()方法会在setItem执行完成后调用,done
都会捕捉到任何可能出现的错误,并向全局抛出
finally则是回调链执行的最后一个方法
AsyncStore全部方法列表参请参考官方文档,或者在你的工程项目中搜索AsyncStore.js查看源码。