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

如何在Redux Persist中将AsyncStorage替换为MMKV?

从AsyncStorage迁移到MMKV(Redux Toolkit持久化改造)

步骤1:安装MMKV依赖

首先安装React Native MMKV包:

npm install react-native-mmkv
# 或使用yarn
yarn add react-native-mmkv

步骤2:修改Store配置代码

直接替换原代码中的AsyncStorage相关逻辑,改用MMKV作为持久化存储,不需要额外自定义set/get方法或中间件(redux-persist会自动处理持久化逻辑)。

修改后的完整代码如下:

import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';
import { profileSlice } from 'features/user/store/profile-slice';
import thunk from 'redux-thunk';
// 替换AsyncStorage导入为MMKV
import { MMKV } from 'react-native-mmkv';
import { garageSlice } from 'features/garage/store/garage-slice';

// 创建MMKV实例
const storage = new MMKV();

const reducers = combineReducers({
  profile: profileSlice.reducer,
  garage: garageSlice.reducer,
});

const persistConfig = {
  key: 'root',
  // 替换storage为MMKV实例
  storage,
};

let middlewares = [thunk];
if (__DEV__) {
  const createDebugger = require('redux-flipper').default;
  middlewares = [...middlewares, createDebugger()];
}

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: persistedReducer,
  devTools: process.env.NODE_ENV !== 'production',
  middleware: middlewares,
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

关键修改点说明

  • 移除@react-native-async-storage/async-storage的导入,替换为react-native-mmkv的MMKV类
  • 创建MMKV实例作为持久化存储引擎,传入persistConfig的storage字段
  • 无需额外添加自定义中间件或set/get方法,redux-persist会基于MMKV自动完成状态的持久化与恢复

额外说明

由于你的应用尚未发布,无需保留用户数据,所以不需要做旧数据迁移操作,直接替换后新的状态会存储在MMKV中,原AsyncStorage的数据可以忽略(后续可以清理,但不影响新逻辑运行)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:02:12