简介
-
AsyncStorage
是一个简单的、异步的、持久化的 Key-Value 存储系统,它对于 App 来说是全局性的。可用来代替 LocalStorage。 -
官方建议我们最好针对 AsyncStorage 进行一下抽象的封装再使用,而不是直接使用 AsyncStorage。
-
在 iOS 上,
AsyncStorage
在原生端的实现是把较小值存放在序列化的字典中,而把较大值写入单独的文件。在 Android 上,AsyncStorage
会尝试使用 RocksDB,或退而选择 SQLite。
方法
-
getItem()
static getItem(key: string, [callback]: ?(error: ?Error, result: ?string) => void)
根据键来获取值,获取的结果会放在回调函数中。 -
setItem()
static setItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
根据键来设置值。 -
removeItem()
static removeItem(key: string, [callback]: ?(error: ?Error) => void)
根据键来移除项。 -
mergeItem()
static mergeItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
合并现有值和输入值。 -
clear()
static clear([callback]: ?(error: ?Error) => void)
清空全部的AsyncStorage数据,不论来自什么库或调用者。 -
getAllKeys()
static getAllKeys([callback]: ?(error: ?Error, keys: ?Array<string>) => void)
获取所有本应用可以访问到的数据,不论来自什么库或调用者。 -
flushGetRequests()
static flushGetRequests(): [object Object]
清除所有进行中的查询操作。 -
multiGet()
static multiGet(keys: Array<string>, [callback]: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void)
获取多项,其中 keys 是字符串数组,比如:['k1', 'k2'] -
multiSet()
static multiSet(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)
设置多项,其中 keyValuePairs 是字符串的二维数组,比如:[['k1', 'val1'], ['k2', 'val2']] -
multiRemove()
static multiRemove(keys: Array<string>, [callback]: ?(errors: ?Array<Error>) => void)
删除多项,其中 keys 是字符串数组,比如:['k1', 'k2']
- multiMerge()
static multiMerge(keyValuePairs: Array<Array<string>>, [callback]: ?(errors: ?Array<Error>) => void)
多个键值合并,其中 keyValuePairs 是字符串的二维数组,比如:[['k1', 'val1'], ['k2', 'val2']]
实例
1. 效果图
(1)在文本输入框中输入姓名、电话后,点击“保存”按钮即可通过 AsyncStorage 存储起来。
(2)退出程序后再次打开,程序又会自动加载之前保存的信息。
(3)点击“清除”按钮则将本地保存的数据全部清除。
img02.jpg
2. 样例代码
组件
import React, {Component} from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
AsyncStorage
} from 'react-native';
export default class UserInfo extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
phone: ''
}
}
componentDidMount() {
var _that = this;
var keys = ['name', 'phone'];
AsyncStorage.multiGet(keys, function (errs, result) {
if (errs) {
return;
}
_that.setState({
name: (result[0][1] != null) ? result[0][1] : '',
phone: (result[1][1] != null) ? result[1][1] : ''
});
});
}
render() {
return (
<View style={styles.flex}>
<View style={styles.row}>
<View style={styles.head}>
<Text style={styles.label}>name</Text>
</View>
<View style={styles.flex}>
<TextInput style={styles.input}
value={this.state.name}
onChangeText={(name) => this.setState({name})}/>
</View>
</View>
<View style={styles.row}>
<View style={styles.head}>
<Text style={styles.label}>phone</Text>
</View>
<View style={styles.flex}>
<TextInput style={styles.input}
value={this.state.phone}
onChangeText={(phone) => this.setState({phone})}/>
</View>
</View>
<View style={styles.row}>
<Text style={styles.btn} onPress={this.save.bind(this)}>save</Text>
<Text style={styles.btn} onPress={this.clear.bind(this)}>clear</Text>
</View>
</View>
);
}
//保存数据
save() {
//设置多项
var keyValuePairs = [
['name', this.state.name],
['phone', this.state.phone]
]
AsyncStorage.multiSet(keyValuePairs, function (errs) {
if (errs) {
//TODO:存储出错
return;
}
alert('数据保存成功!');
});
}
//清除数据
clear() {
var _that = this;
AsyncStorage.clear(function(err){
if(!err){
_that.setState({
name: "",
phone: ""
});
alert('存储的数据已清除完毕!');
}
});
}
}
const styles = StyleSheet.create({
flex: {
flex: 1,
},
topStatus: {
marginTop: 25,
},
row: {
flexDirection: 'row',
height: 45,
marginBottom: 10
},
head: {
width: 70,
marginLeft: 5,
backgroundColor: '#23BEFF',
height: 45,
justifyContent: 'center',
alignItems: 'center'
},
label: {
color: '#fff',
fontSize: 15,
fontWeight: 'bold'
},
input: {
height: 45,
borderWidth: 1,
marginRight: 5,
paddingLeft: 10,
borderColor: '#ccc'
},
btn: {
flex: 1,
backgroundColor: '#FF7200',
height: 45,
textAlign: 'center',
color: '#fff',
marginLeft: 5,
marginRight: 5,
lineHeight: 45,
fontSize: 15,
},
});
使用
import React, {Component} from 'react';
import {
StyleSheet,
View,
} from 'react-native';
import UserInfo from './src/UserInfo';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<UserInfo/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop:25,
backgroundColor: '#F5FCFF',
},
});
参考
相关文章:
AsyncStorage ·React Native 中文网
从零学React Native之13 持久化存储
《ReactNative》之sqlite
React Native调用原生端sqlite数据库
网友评论