1.安装依赖:
npm install redux-persist
2. 基础配置:
// store.js
import { configureStore } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // 默认是 localStorage// 持久化配置
const persistConfig = {key: 'root', // 存储的键名storage, // 存储方式whitelist: ['user', 'settings'], // 需要持久化的reducerblacklist: ['temp'] // 不需要持久化的reducer
}// 包装 reducer
const persistedReducer = persistReducer(persistConfig, rootReducer)// 创建 store
export const store = configureStore({reducer: persistedReducer,middleware: (getDefaultMiddleware) =>getDefaultMiddleware({serializableCheck: {// 忽略 redux-persist 的动作类型ignoredActions: ['persist/PERSIST']}})
})// 创建持久化 store
export const persistor = persistStore(store)
3.在应用中使用:
// App.jsx
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
import { store, persistor } from './store'function App() {return (<Provider store={store}><PersistGate loading={null} persistor={persistor}><YourApp /></PersistGate></Provider>)
}
4.高级配置:
const persistConfig = {key: 'root',storage,// 数据转换transforms: [encryptTransform({secretKey: 'my-secret-key'})],// 存储版本控制version: 1,migrate: (state) => {// 版本迁移逻辑return Promise.resolve(state)},// 合并策略stateReconciler: autoMergeLevel2
}
5.自定义存储引擎:
// 使用 sessionStorage
import createWebStorage from 'redux-persist/lib/storage/createWebStorage'
const sessionStorage = createWebStorage('session')// 使用 AsyncStorage (React Native)
import AsyncStorage from '@react-native-async-storage/async-storage'const persistConfig = {key: 'root',storage: AsyncStorage
}
6.选择性持久化:
// 单独配置某个 reducer
const userPersistConfig = {key: 'user',storage,whitelist: ['profile', 'preferences']
}const userReducer = persistReducer(userPersistConfig, baseUserReducer)// 在 store 中使用
const store = configureStore({reducer: {user: userReducer,other: otherReducer}
})
7.处理持久化状态:
// 监听持久化状态
persistStore(store, null, () => {console.log('重置完成')
}).purge() // 清除持久化数据// 在组件中使用
function App() {return (<PersistGate loading={<LoadingView />}persistor={persistor}onBeforeLift={() => {// 在恢复数据之前执行}}><YourApp /></PersistGate>)
}
8.实际应用示例:
// userSlice.js
import { createSlice } from '@reduxjs/toolkit'const userSlice = createSlice({name: 'user',initialState: {profile: null,token: null},reducers: {setUser: (state, action) => {state.profile = action.payload},setToken: (state, action) => {state.token = action.payload},logout: (state) => {state.profile = nullstate.token = null}}
})// store.js
const persistConfig = {key: 'user',storage,whitelist: ['token'] // 只持久化 token
}const persistedUserReducer = persistReducer(persistConfig,userSlice.reducer
)// 使用
function App() {const dispatch = useDispatch()const token = useSelector(state => state.user.token)useEffect(() => {if (token) {// 自动登录逻辑}}, [token])return (// ...)
}
主要功能:
- 自动保存状态到存储
- 应用启动时恢复状态
- 选择性持久化
- 版本控制和迁移
- 自定义存储引擎
- 数据转换
使用场景:
1. 用户登录状态
- 应用配置
- 主题设置
- 缓存数据
- 离线功能
注意事项:
- 不要持久化敏感信息
- 控制持久化数据大小
- 处理版本升级
- 考虑清理策略
- 处理错误情况