0Pricing
React Native Academy · 课时

使用 AsyncStorage 读写数据

安装 @react-native-async-storage/async-storage,使用 setItem 和 getItem 存储及读取字符串值,并正确处理返回的 Promise。

使用 AsyncStorage 读写数据 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is AsyncStorage?

AsyncStorage is React Native's persistent key-value storage system. It stores data as strings on the device's local file system, making it available even after the app is closed and reopened. It works on both iOS and Android and supports any string-serializable value. All operations are asynchronous and return Promises, so you must await them or chain .then().

Installing the Package

The community AsyncStorage package must be installed separately in modern React Native and Expo projects. It is no longer bundled with React Native core. Use npx expo install (instead of plain npm) so Expo picks the compatible version for your SDK.

npx expo install @react-native-async-storage/async-storage

Writing Data with setItem

AsyncStorage.setItem(key, value) stores a string value at the given key. Both the key and the value must be strings. If the key already exists, the value is overwritten. Always await the call inside a try-catch block to handle potential errors, such as storage being full on the device.

import AsyncStorage from '@react-native-async-storage/async-storage';

async function saveUsername(username: string) {
  try {
    await AsyncStorage.setItem('username', username);
    console.log('Saved successfully');
  } catch (error) {
    console.error('Failed to save username:', error);
  }
}

Reading Data with getItem

AsyncStorage.getItem(key) retrieves the string value for the given key. It returns null if the key does not exist — handle this case to avoid runtime errors. A common pattern is to check for null and fall back to a default value when the app launches for the first time.

async function loadUsername(): Promise<string> {
  try {
    const value = await AsyncStorage.getItem('username');
    if (value !== null) {
      return value;
    }
    return 'Guest'; // default when key does not exist
  } catch (error) {
    console.error('Failed to load username:', error);
    return 'Guest';
  }
}

Removing Data with removeItem

AsyncStorage.removeItem(key) deletes the entry for the given key from storage. After removal, calling getItem for that key returns null. Use this when the user logs out, resets preferences, or deletes their account — any time you need to erase specific stored data without clearing everything.

async function clearSession() {
  try {
    await AsyncStorage.removeItem('authToken');
    await AsyncStorage.removeItem('userId');
    console.log('Session cleared');
  } catch (error) {
    console.error('Failed to clear session:', error);
  }
}

Loading Data on App Start with useEffect

A typical pattern is to load persisted data into component state when a screen mounts. Use useEffect with an empty dependency array so it runs only once on mount. Set a loading flag while the data loads and clear it when the read completes so the UI shows a spinner instead of blank or stale content.

export default function SettingsScreen() {
  const [theme, setTheme] = React.useState('light');
  const [loading, setLoading] = React.useState(true);

  useEffect(() => {
    async function loadTheme() {
      const saved = await AsyncStorage.getItem('theme');
      if (saved) setTheme(saved);
      setLoading(false);
    }
    loadTheme();
  }, []);

  if (loading) return <ActivityIndicator />;
  return <Text>Current theme: {theme}</Text>;
}

Batch Operations with multiSet and multiGet

Reading or writing several keys in a loop is inefficient. Use AsyncStorage.multiSet and AsyncStorage.multiGet to perform batch operations in a single native call. multiSet accepts an array of [key, value] pairs, and multiGet returns an array of the same format with the retrieved values.

// Write multiple keys in one call
await AsyncStorage.multiSet([
  ['theme', 'dark'],
  ['language', 'en'],
  ['fontSize', '16'],
]);

// Read multiple keys in one call
const pairs = await AsyncStorage.multiGet(['theme', 'language', 'fontSize']);
const settings = Object.fromEntries(pairs);
console.log(settings); // { theme: 'dark', language: 'en', fontSize: '16' }

Listing All Keys

AsyncStorage.getAllKeys() returns an array of every key currently stored by the app. This is useful for debugging, for building a cache-clearing screen, or for reading all entries without knowing the keys in advance. Combine it with multiGet to load the full storage contents at once.

async function debugStorage() {
  const keys = await AsyncStorage.getAllKeys();
  console.log('All keys:', keys);
  const pairs = await AsyncStorage.multiGet(keys);
  pairs.forEach(([key, value]) => {
    console.log(key, '->', value);
  });
}

Clearing All Data with clear

AsyncStorage.clear() deletes all keys stored by the app. Use this with caution — it is a destructive operation with no built-in undo. It is appropriate for a factory reset feature or for wiping all data during development, but never call it without explicit user confirmation in a production app.

async function factoryReset() {
  Alert.alert('Reset App', 'This will delete all your data. Are you sure?', [
    { text: 'Cancel', style: 'cancel' },
    {
      text: 'Reset',
      style: 'destructive',
      onPress: async () => {
        await AsyncStorage.clear();
        navigation.reset({ index: 0, routes: [{ name: 'Onboarding' }] });
      },
    },
  ]);
}

Error Handling Best Practices

AsyncStorage operations can fail when the device is low on storage or when a native bridge error occurs. Always wrap reads and writes in try-catch blocks. For reads, return a sensible default on error. For writes, consider queuing the write to retry later or notifying the user that their setting could not be saved.

async function safeSave(key: string, value: string) {
  try {
    await AsyncStorage.setItem(key, value);
    return true;
  } catch (err) {
    if (__DEV__) console.error('AsyncStorage write failed:', err);
    // Optionally: show a Snackbar or Toast to the user
    return false;
  }
}

AsyncStorage Limits and Alternatives

AsyncStorage is designed for small amounts of data — user preferences, tokens, and simple settings. It is not suitable for large datasets (images, documents, or thousands of records), for which you should consider SQLite (via expo-sqlite). Also note that AsyncStorage data is not encrypted by default, so use Expo SecureStore for sensitive credentials.

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: setItem and getItem are the core AsyncStorage APIs for writing and reading string values keyed by name, multiSet and multiGet batch multiple operations into a single efficient native call, and null checking is essential because getItem returns null for keys that have never been written. Next up we explore storing and parsing JSON objects in AsyncStorage.

常见问题解答

「使用 AsyncStorage 读写数据」课时是免费的吗?

是的 — 「使用 AsyncStorage 读写数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「使用 AsyncStorage 读写数据」这节课中我会学到什么?

安装 @react-native-async-storage/async-storage,使用 setItem 和 getItem 存储及读取字符串值,并正确处理返回的 Promise。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 AsyncStorage 读写数据」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 AsyncStorage 读写数据
  2. 存储并解析 JSON 对象
  3. 构建持久化设置屏幕
  4. 清除存储与迁移策略
← 返回 React Native Academy