[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

轉載請著名出處!謝謝~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM