You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中是否有localStorage的等效实现方案?

React Native 实现 localStorage 等效功能的方案

在 React Native 里没有浏览器的 localStorage,但有几个成熟的持久化存储方案可以替代,以下是最常用的两种:

1. AsyncStorage(官方推荐)

这是官方维护的异步键值存储库,功能和 localStorage 类似,数据会持久化保存,重启应用后依然存在。

步骤:

  • 安装依赖:
    npm install @react-native-async-storage/async-storage
    # 或者用 yarn
    yarn add @react-native-async-storage/async-storage
    
  • 基础用法:
    • 存储数据:
      import AsyncStorage from '@react-native-async-storage/async-storage';
      
      const saveData = async (key, data) => {
        try {
          // 复杂数据要转成 JSON 字符串存储
          const jsonStr = JSON.stringify(data);
          await AsyncStorage.setItem(key, jsonStr);
        } catch (err) {
          console.log('存储出错:', err);
        }
      };
      
    • 获取数据:
      const loadData = async (key) => {
        try {
          const jsonStr = await AsyncStorage.getItem(key);
          // 解析回原数据格式,没有数据返回 null
          return jsonStr ? JSON.parse(jsonStr) : null;
        } catch (err) {
          console.log('获取出错:', err);
        }
      };
      
    • 删除数据:
      const deleteData = async (key) => {
        try {
          await AsyncStorage.removeItem(key);
        } catch (err) {
          console.log('删除出错:', err);
        }
      };
      

2. MMKV(高性能替代)

如果你的应用需要频繁读写数据,推荐用 MMKV——腾讯开源的键值存储库,性能比 AsyncStorage 好很多,支持同步操作,不用写 async/await。

步骤:

  • 安装依赖:
    npm install react-native-mmkv
    # 或者用 yarn
    yarn add react-native-mmkv
    
  • 基础用法:
    import { MMKV } from 'react-native-mmkv';
    
    // 创建一个存储实例
    const storage = new MMKV();
    
    // 存储数据(支持直接存字符串,复杂数据要转 JSON)
    storage.set('user_info', JSON.stringify({ name: 'Alice', age: 25 }));
    
    // 获取数据
    const userInfo = storage.getString('user_info') ? JSON.parse(storage.getString('user_info')) : {};
    
    // 删除数据
    storage.delete('user_info');
    

注意事项:

  • 不要用这些存储方案存敏感数据(比如密码、token),敏感数据建议用系统的密钥链(iOS Keychain/Android Keystore)相关库处理。
  • 避免存储过大的数据,防止拖慢应用启动或运行速度。

内容的提问来源于stack exchange,提问作者Hailemelekot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:57:15