RN:本地存储@react-native-async-storage/async-storage

背景

在这里插入图片描述
可以看到,官方的库已过时,建议我们去社区仓库选择一个,我们选择这个,也是 ignite 脚手架推荐的:
https://github.com/react-native-async-storage/async-storage

使用

yarn add @react-native-async-storage/async-storage --save
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeData = async (value) => {try {await AsyncStorage.setItem('@storage_Key', value)} catch (e) {// saving error}
}

写起来比较麻烦,所以我们要在项目里封装一层

封装

import AsyncStorage from '@react-native-async-storage/async-storage';/*** Loads a string from storage.** @param key The key to fetch.*/
export async function loadString(key: string): Promise<string | null> {try {return await AsyncStorage.getItem(key);} catch {// not sure why this would fail... even reading the RN docs I'm unclearreturn null;}
};/*** Saves a string to storage.** @param key The key to fetch.* @param value The value to store.*/
export async function saveString(key: string, value: string): Promise<boolean> {try {await AsyncStorage.setItem(key, value);return true;} catch {return false;}
}/*** Loads something from storage and runs it thru JSON.parse.** @param key The key to fetch.*/
export async function load(key: string): Promise<any | null> {try {const almostThere = await AsyncStorage.getItem(key)return JSON.parse(almostThere);} catch {return null;}
}/*** Saves an object to storage.** @param key The key to fetch.* @param value The value to store.*/
export async function save(key: string, value: any): Promise<boolean> {try {await AsyncStorage.setItem(key, JSON.stringify(value));return true;} catch {return false;}
}/*** Removes something from storage.** @param key The key to kill.*/
export async function remove(key: string): Promise<void> {try {await AsyncStorage.removeItem(key);} catch {}
}/*** Burn it all to the ground.*/
export async function clear(): Promise<void> {try {await AsyncStorage.clear();} catch {}
}export async function exist(key: string): Promise<boolean> {try {const item = await AsyncStorage.getItem(key);return !!item;} catch {return false;}
}

使用

import * as storage from '@/utils/storage';
await storage.save("Cool Name", "Boaty McBoatface")import { save } from '@/utils/storage';
await save("Cool Name", "Boaty McBoatface")import { save as storageSave } from '@/utils/storage';
await storageSave("Cool Name", "Boaty McBoatface")


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部