【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); //读取