React-native 之 AsyncStorage学习

来源:互联网 发布:归结原理算法实验 编辑:程序博客网 时间:2024/05/22 17:30

AsyncStorage 是react-native 用来做异步存储使用的 ,它的所有的api都有一个回调方法,回调方法的第一个参数是error,显示错误信息,如果没有错误则为 null ,AsyncStorage 返回的都是一个Promise 对象 ,一下是一些比较常用到的API


  • static getItem(key:string , callback:(error,result)): 根据键来获取值,获取的结果会在回调函数中。
  • static setItem(key:string , value:string , callback:(error)): 设置键值对。
  • static removeItem(key:string , callback:(error)): 将根据键移出一项
  • static mergeItem:(key:string , value:string , callback:(error)): 合并现有的值和输入值。
  • static clear(callback:(error)): 清除所有的项目。
  • static getAllKeys(callback:(error)): 获取所有的键。
  • static multiGet(keys,callback:(errors,result)):获取多项,其中keys是字符串数组。
  • static multiSet(keyValuePairs,callback:(errors)):设置多项,其中keyValuePairs是字符串的二维数组。
  • static multiRemove(keys,callback(errors)):删除多项,其中keys是字符串数组。
  • static multiMerge(keyValuePairs,callback:(errors)):多个键值合并,其中keyValuePairs是字符串中的二维数组。


'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  AsyncStorage,
  TouchableHighlight,
} from 'react-native';
varSTORAGE_KEY_ONE = '@AsyncStorageDemo:key_one';
varSTORAGE_KEY_MESSAGE = '@AsyncStorageDemo:key_message';
//简单封装一个组件
class CustomButton extends React.Component {
  render() {
    return(
      <TouchableHighlight
        style={styles.button}
        underlayColor="#a5a5a5"
        onPress={this.props.onPress}>
        <Text style={styles.buttonText}>{this.props.text}</Text>
      </TouchableHighlight>
    );
  }
}
class AsyncStorageDemo extends Component {
  constructor(props){
    super(props);
    this.state={
        messages:[],
    };
  }
  //组件挂载之后回调方法
  componentDidMount(){
       this._loadInitialState().done();
  }
  //初始化数据-默认从AsyncStorage中获取数据
  async _loadInitialState(){
       try{
          varvalue=await AsyncStorage.getItem(STORAGE_KEY_ONE);
          if(value!=null){
            this._appendMessage('从存储中获取到数据为:'+value);
          }else{
            this._appendMessage('存储中无数据,初始化为空数据');
          }
       }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
       }
  }
  //进行储存数据_ONE
  async _saveValue_One(){
      try{
         await AsyncStorage.setItem(STORAGE_KEY_ONE,'我是老王');
         this._appendMessage('保存到存储的数据为:'+'我是老王');
      }catch(error){
         this._appendMessage('AsyncStorage错误'+error.message);
      }
  }
  //进行存储数据删除_ONE
  async _removeValue_One(){
      try{
         await AsyncStorage.removeItem(STORAGE_KEY_ONE);
         this._appendMessage('数据删除成功...');
      }catch(error){
         this._appendMessage('AsyncStorage错误'+error.message);
      }
  }
  //进行把message信息添加到messages数组中
  _appendMessage(message){
     this.setState({messages:this.state.messages.concat(message)});
  }
  render() {
    return(
      <View>
        <Text style={styles.welcome}>
           AsyncStorage使用实例
        </Text>
        <CustomButton text='点击存储数据_我是老王'onPress={this._saveValue_One}/>
        <CustomButton text='点击删除数据'onPress={this._removeValue_One}/>
        <Text style={styles.content}>信息为:</Text>
        {this.state.messages.map((m) => <Text style={styles.content} key={m}>{m}</Text>)}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  welcome: {
    fontSize: 14,
    textAlign:'left',
    margin: 10,
  },
  content:{
    fontSize: 13,
    textAlign:'left',
    margin: 10,
  },
   button: {
    margin:5,
    backgroundColor:'white',
    padding: 15,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor:'#cdcdcd',
  }
});
 
AppRegistry.registerComponent('AsyncStorageDemo', () => AsyncStorageDemo);


0 0
原创粉丝点击