之前写过一篇异步获取的,但是不能满足开发中,同步读取的需求。链接: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); //读取

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
  • 2021-05-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-28
  • 2021-10-11
  • 2022-02-12
  • 2021-10-01
  • 2022-12-23
  • 2021-07-19
相关资源
相似解决方案