RN-AsyncStorage

基本概念

1 AsyncStorage

* AsyncStorage 是一个简单的、异步的、持久化的 Key-Value 存储系统,它对于 App 来说是全局性的。它用来代替 LocalStorage。
* 由于它的操作是全局的,官方建议我们最好针对 AsyncStorage 进行一下抽象的封装再使用,而且不是直接拿 AsyncStorage 进行使用。 (react-native-storage)
* AsyncStorage 存储的位置根据系统的不同而有所差异。iOS 中的存储类似于 NSUserDefault,通过 plist 文件存放在设备中。Android 中会存储在 RocksDB 或者 SQLite 中,取决于你使用哪个。

2 相关方法

根据键来获取值, 获取的值放在回调函数中

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, keys))

清除所有进行中的查询操作。

static flushGetRequests()

获取多项,其中 keys 是字符串数组,比如:['k1', 'k2']

static multiGet(keys, callback:(errors, result))

设置多项,其中 keyValuePairs 是字符串的二维数组,比如:[['k1', 'val1'], ['k2', 'val2']]

static multiSet(keyValuePairs, callback:(errors))

删除多项,其中 keys 是字符串数组,比如:['k1', 'k2']

static multiRemove(keys, callback:(errors))

多个键值合并,其中 keyValuePairs 是字符串的二维数组,比如:[['k1', 'val1'], ['k2', 'val2']]

static multiMerge(keyValuePairs, callback:(errors))

3 使用

/**
 * Created by licc on 2017/7/13.
 */

import React, { Component }from  'react';
import  {
    AsyncStorage,
    Button,
    View,
    Text,
    TextInput,
    TouchableHighlight,
    StyleSheet
} from  'react-native';

import NavigationBar from './NavigationBar'

export default class AsyncStorageExample extends Component {

    constructor(props){
        super(props);

        this.state = {
            username:'',
            password:''
        }
    }

    componentDidMount(){

        var keys = ['username', 'password'];
        AsyncStorage.multiGet(keys, (errs, result)=>{

            var _that = this;

            if (errs) return;

            _that.setState({
                username:(result[0][1]!== null)? result[0][1]:'',
                password:(result[1][1]!== null)? result[1][1]:''
            });
        });
    }

    render(){
        return (
            <View>
                <NavigationBar
                    title={'登录'}
                    statusBar={{backgroundColor:'blue'}}
                />
                <View style={styles.row}>

                    <View style={styles.head}>
                        <Text style={styles.label}>用户名</Text>
                    </View>

                    <View style={styles.flex}>
                        <TextInput
                            style={styles.input}
                            value = {this.state.username}
                            onChangeText={(username)=>this.setState({username})}
                        />
                    </View>

                </View>


                <View style={styles.row}>

                    <View style={styles.head}>
                        <Text style={styles.label}>密码</Text>
                    </View>

                    <View style={styles.flex}>
                        <TextInput
                            style={styles.input}
                            value={this.state.password}
                            onChangeText={(password)=>this.setState({password})}
                        />
                    </View>

                </View>


                <View style={styles.row}>
                        <Text style={styles.btn} onPress={this.doLogin.bind(this)}>登录</Text>
                        <Text style={styles.btn} onPress={this.clear.bind(this)}>清除</Text>
                </View>

            </View>
        );
    }


    doLogin(){

       let info = [['username', this.state.username], ['password', this.state.password]]

        AsyncStorage.multiSet(info, (errs)=>{
            if (errs) {
                alert('登录失败');
                return;
            }

            alert('登录成功');
        });
    }

    clear(){
        AsyncStorage.clear((errs)=>{
           if (!errs){
               this.setState({
                   username:'',
                   password:''
               });

               alert('存储的数据已清除完毕!');
           }
        });
    }




}

const styles = StyleSheet.create({

    flex:{
        flex:1,
    },

    topStatus:{
        marginTop:25,
    },

    row:{
        flexDirection:'row',
        height:55,
        paddingTop:10
    },

    head:{
        width:80,
        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,
    },

});

*注 第三方封装
react-native-storage

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容