[RN] React Native 使用 AsyncStorage 存储 缓存数据

 React Native 使用 AsyncStorage 存储 缓存数据

AsyncStorage是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。这是官网上对它的介绍。可以知道,这个asyncstorage也是以键值对的形式进行存储数据的。   那么问题来了,该怎么使用这个呢?官网上说并不推荐我们直接用这个asyncstorage,而是进行抽象封装以后在进行调用。

封装类 StorageUtil.js   代码如下:

import {AsyncStorage} from 'react-native';

class StorageUtil {

    /**
     * 获取
     * @param key
     * @returns {*|Promise<*>|PromiseLike<T | never>|Promise<T | never>}
     */
    static get(key) {
        return AsyncStorage.getItem(key).then((value) => {
            const jsonValue = JSON.parse(value);
            return jsonValue;
        });
    }

    /**
     * 保存
     * @param key
     * @param value
     * @returns {*}
     */
    static save(key, value) {
        return AsyncStorage.setItem(key, JSON.stringify(value));
    }

    /**
     * 更新
     * @param key
     * @param value
     * @returns {*}
     */
    static update(key, value) {
        return AsyncStorage.setItem(key, JSON.stringify(value));
    }

    /**
     * 删除
     * @param key
     * @returns {*}
     */
    static delete(key) {
        return AsyncStorage.removeItem(key);
    }

    /**
     * 删除所有配置数据
     * @returns {Promise<string>}
     */
    static clear() {
        return AsyncStorage.clear();
    }

}

export default StorageUtil;

使用代码:

let key = 'per';
        let person = "hello";

        //保存
        StorageUtil.save(key, person);

        //获取
        StorageUtil.get(key).then((row)=>{
            if(row){
                console.log(row)
            }else{
                console.log("null")
            }

        });

        //更新
        let person2 = "广州";
        StorageUtil.update(key, person2);

        // StorageUtil.delete(key);

        //清除所有
        StorageUtil.clear();

        StorageUtil.get(key).then((row)=>{
            if(row){
                alert(row);
                console.log(row)
            }else{
                console.log("null")
            }
        });

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/10958297.html

转载请著名出处!谢谢~~

原文地址:https://www.cnblogs.com/wukong1688/p/10958297.html