【React Native】同步获取本地缓存键值对


  之前写过一篇异步获取的,但是不能满足开发中,同步读取的需求。链接:https://www.cnblogs.com/xjf125/p/10456720.html

  今天封装了一个同步获取本地键值对。

import React from "react";
import {
    AsyncStorage
} from 'react-native';
export default class SyncStorage {

    static cache: { [key: string]: string } = {}


    static async init() {
        let keys = await AsyncStorage.getAllKeys()
        let items = await AsyncStorage.multiGet(keys).then()
        items.map(([key, value]) => {
            this.cache[key] = value
        })
    }

    static getValue(key: string) {
        return this.cache[key]
    }

    static setValue(key: string, value: string) {
        if (this.cache[key] === value) return
        this.cache[key] = value
        AsyncStorage.setItem(key, value)
    }

    static removeKey(key: string) {
        delete this.cache[key]
        AsyncStorage.removeItem(key)
    }
}

  使用:

SyncStorage.setValue(key,digest);  //写入

lastText = SyncStorage.getValue(key); //读取

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM