AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替LocalStorage
效果图如下
代码:
/**
* Created by sunbiao on 2017/7/20.
*/
import React, {Component} from 'react';
import {
StyleSheet,
View,
AsyncStorage,
Button,
Alert,
Text,
TextInput,
} from 'react-native';
export default class AsyncStorageDemo extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
key:'a',
value:'1',
data:'',
};
this._catchError=this._catchError.bind(this);
}
_addData(){
AsyncStorage.setItem(this.state.key,this.state.value,(error)=>this._catchError(error))
}
_catchError(error){
if (error == null){
Alert.alert('success')
} else {
Alert.alert('falure')
}
}
_getData(){
var that = this;
AsyncStorage.getItem(this.state.key,(error,result)=>{
if (error == null){
Alert.alert('key:'+this.state.key+' value:'+result)
} else {
Alert.alert('falure')
}
})
}
_getAllkey(){
this.setState({data: ''});
AsyncStorage.getAllKeys(
(error,keys)=>{
if (keys && keys.length>0){
keys.map((key, i)=>{
AsyncStorage.getItem(key,(error,result)=>{
if (error==null) {
var data= 'key:'+this.state.key+' value:'+result;
Alert.alert(data)
this.setState({
data:data
})
}
})
})
}
}
)
}
_removeData(){
AsyncStorage.removeItem(this.state.key,(error)=>{
if (error == null){
Alert.alert('success')
} else {
Alert.alert('falure')
}
})
}
render(){
return(
<View style={{flex:1,margin:20}}>
<Button title='store' onPress={this._addData.bind(this)}/>
<Button title='getData' onPress={this._getData.bind(this)}/>
<Button title='AllData' onPress={this._getAllkey.bind(this)}/>
<Button title='remove' onPress={this._removeData.bind(this)}/>
</View>
);
}
}