背景

在这里插入图片描述
可以看到,官方的库已过时,建议我们去社区仓库选择一个,我们选择这个,也是 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 unclear
    return 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")
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐