AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。
我们推荐您在AsyncStorage的基础上做一层抽象封装,而不是直接使用AsyncStorage。
主要使用到的方法有:
- static getItem(key: string, callback?: ?(error: ?Error, result: ?string) => void)
读取key字段并将结果作为第二个参数传递给callback。如果有任何错误发生,则会传递一个Error对象作为第一个参数。返回一个Promise对象。 - static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)
将key字段的值设置成value,并在完成后调用callback函数。如果有任何错误发生,则会传递一个Error对象作为第一个参数。返回一个Promise对象。
- static removeItem(key: string, callback?: ?(error: ?Error) => void)
删除一个字段。返回一个Promise对象。
- static mergeItem(key: string, value: string, callback?: ?(error: ?Error) => void)
假设已有的值和新的值都是字符串化的JSON,则将两个值合并。返回一个Promise对象。还没有被所有原生实现都支持。
- static clear(callback?: ?(error: ?Error) => void)
删除全部的AsyncStorage数据,不论来自什么库或调用者。通常不应该调用这个函数——使用removeItem或者multiRemove来清除你自己的key。返回一个Promise对象。
更多可以http://reactnative.cn/docs/0.20/asyncstorage.html。
示例DEMO:
//noinspection JSUnresolvedVariable
import React, {Component} from 'react'
//noinspection JSUnresolvedVariable
import {
AppRegistry,
StyleSheet,
View,
TextInput,
AsyncStorage,
Text
} from 'react-native';
import Toast,{DURATION} from 'react-native-easy-toast'; //引入Toast控件
//AsyncStorage是以键值对的形式保存数据 ,诸如安卓中SharedPreferences一样
const AS_KEY = "as_key";
export default class AsyncStoreDemo extends Component {
constructor(props) {
super(props);
}
//保存数据
asSave() {
AsyncStorage.setItem(AS_KEY, this.text, (error) => {
if (!error) {
this.toast.show('保存数据成功', DURATION.LENGTH_SHORT);
} else {
this.toast.show('保存数据失败', DURATION.LENGTH_SHORT);
}
})
}
//查询保存的数据
asQuery() {
AsyncStorage.getItem(AS_KEY, (error, result) => {
if (!error) {
if (result !== '' && result !== null) {
this.toast.show('查询到的内容是:' + result, DURATION.LENGTH_SHORT);
} else {
this.toast.show('未找到指定保存的内容!', DURATION.LENGTH_SHORT);
}
} else {
this.toast.show('查询数据失败', DURATION.LENGTH_SHORT);
}
})
}
//删除已经保存的数据
asDelete() {
AsyncStorage.removeItem(AS_KEY, (error) => {
if (!error) {
this.toast.show('删除数据成功', DURATION.LENGTH_SHORT);
} else {
this.toast.show('删除数据失败', DURATION.LENGTH_SHORT);
}
})
}
render() {
return (<View style={styles.container}>
<TextInput style={styles.edit}
//文字内容发生改变调用方法
onChangeText={text=>this.text=text}/>
<View style={styles.child}>
<Text style={styles.text}
onPress={()=>{
this.asSave()
}}>保存</Text>
<Text style={styles.text}
onPress={()=>{
this.asQuery()
}}>查询</Text>
<Text style={styles.text} onPress={()=>{
this.asDelete()
}}>删除</Text>
</View>
<Toast ref={toast=>{
this.toast=toast
}}/>
</View>);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
child: {
flexDirection: 'row'
},
edit: {
fontSize: 20,
borderWidth: 1,
borderColor: '#d1d1d1',
margin: 10,
paddingLeft: 5,
height: 45,
borderRadius:3
},
text: {
fontSize: 20,
color: '#333',
marginLeft: 15
}
});