React-Native开发七 react-navigation之AsyncStorage数据存储

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qiyei2009/article/details/81415229

1 前言

我们都知道,在Android和IOS中分别有不同的持久化数据方式,例如Android中的文件,数据库,SharePrefences等。AsyncStorage是一个简单的key-value存储系统,是RN官方推荐的。它存储的都是String类型的数据,是一个RN中轻量级的数据持久化技术

2 AsyncStorage主要用法

export const AsyncStorage: AsyncStorageStatic;
export type AsyncStorage = AsyncStorageStatic;

/**
 * AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage
 * system that is global to the app.  It should be used instead of LocalStorage.
 *
 * It is recommended that you use an abstraction on top of `AsyncStorage`
 * instead of `AsyncStorage` directly for anything more than light usage since
 * it operates globally.
 *
 * On iOS, `AsyncStorage` is backed by native code that stores small values in a
 * serialized dictionary and larger values in separate files. On Android,
 * `AsyncStorage` will use either [RocksDB](http://rocksdb.org/) or SQLite
 * based on what is available.
 *
 * @see https://facebook.github.io/react-native/docs/asyncstorage.html#content
 */
export interface AsyncStorageStatic {
    /**
     * Fetches key and passes the result to callback, along with an Error if there is any.
     */
    getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;

    /**
     * Sets value for key and calls callback on completion, along with an Error if there is any
     */
    setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;

    /**
     * Merges existing value with input value, assuming they are stringified json. Returns a Promise object.
     * Not supported by all native implementation
     */
    mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    /**
     * Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this.
     * Use removeItem or multiRemove to clear only your own keys instead.
     */
    clear(callback?: (error?: Error) => void): Promise<void>;

    /**
     * Gets all keys known to the app, for all callers, libraries, etc
     */
    getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise<string[]>;

    /**
     * multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet
     */
    multiGet(
        keys: string[],
        callback?: (errors?: Error[], result?: [string, string][]) => void
    ): Promise<[string, string][]>;

    /**
     * multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet,
     *
     * multiSet([['k1', 'val1'], ['k2', 'val2']], cb);
     */
    multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;

    /**
     * Delete all the keys in the keys array.
     */
    multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise<void>;

    /**
     * Merges existing values with input values, assuming they are stringified json.
     * Returns a Promise object.
     *
     * Not supported by all native implementations.
     */
    multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;
}

可以看到AsyncStorage存储的都是String-String类型,和Android中的SharePrefences很像,在js中如果需要存储对象,需要使用JSON序列化进行存储。好在js中对象的定义就是符合JSON对象的形式的,因此序列化起来非常方便。

3 AsyncStorage Demo实例

在使用AsyncStorage时,我们需要从react-native中导入该组件,下面以常用的getItem,setItem,removeItem为例,来讲解基本使用。先来看api介绍

    /**
     * Fetches key and passes the result to callback, along with an Error if there is any.
     */
    getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string>;

    /**
     * Sets value for key and calls callback on completion, along with an Error if there is any
     */
    setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

    removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;

getItem对应获取数据,参数是传入一个key,然后有一个回调,如果是错误的话error不为null,否则读取result
setItem对应存储数据,需要传输key,数据以及错误的回调
removeItem对象删除数据,需要传入key以及对应的错误的回调。
下面看Demo源码

import React,{Component}from "react";
import {View,TouchableOpacity, Text, TextInput, AsyncStorage} from "react-native";
import Toast, {DURATION} from 'react-native-easy-toast'

const KEY = "key";

export default class AsyncStorageDemo extends Component{


    constructor(props){
        super(props);
    }

    render(){
        return (
            <View>
                {/*赋值给AsyncStorageDemo.text变量*/}
                <TextInput onChangeText={(text) => this.text=text}/>
                <View style={{flexDirection:"row",justifyContent:"space-between", margin:10}}>
                    <TouchableOpacity onPress={() => this.onSave()}>
                        <Text>保存</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.onRemove()}>
                        <Text>删除</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.onFetch()}>
                        <Text>获取</Text>
                    </TouchableOpacity>
                </View>
                <Toast ref={(toast) => this.toast = toast}/>
            </View>
        );
    }

    onSave(){
        AsyncStorage.setItem(KEY,this.text,(error) => {
            if (!error){
                this.toast.show("保存成功",DURATION.LENGTH_SHORT);
            } else {
                this.toast.show("保存失败",DURATION.LENGTH_SHORT);
            }
        })
    }

    onRemove(){
        AsyncStorage.removeItem(KEY,(error) => {
            if (!error){
                this.toast.show("删除成功",DURATION.LENGTH_SHORT);
            } else {
                this.toast.show("删除失败",DURATION.LENGTH_SHORT);
            }
        })
    }

    onFetch(){
        AsyncStorage.getItem(KEY,(error,result) => {
            if (!error){
                if (result !== null && result !== ""){
                    this.toast.show("获取成功:" + result,DURATION.LENGTH_SHORT);
                } else {
                    this.toast.show("不存在" + result,DURATION.LENGTH_SHORT);
                }

            } else {
                this.toast.show("获取失败",DURATION.LENGTH_SHORT);
            }
        })
    }
}

代码还是挺简单的,就不做过多讲解了。下面看运行效果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qiyei2009/article/details/81415229