美文网首页
reactNative 学习之AsyncStorage

reactNative 学习之AsyncStorage

作者: Lucky_1122 | 来源:发表于2017-07-20 16:46 被阅读24次

AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替LocalStorage
效果图如下

屏幕快照 2017-07-20 下午4.32.32.png 屏幕快照 2017-07-20 下午4.33.16.png

代码:

/**
 * 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>
          );
      }
}

相关文章

网友评论

      本文标题:reactNative 学习之AsyncStorage

      本文链接:https://www.haomeiwen.com/subject/iqhjkxtx.html