Redux Persist

基本用法

基本用法包括将 persistReducerpersistStore 添加到您的设置中。

重要提示:每个应用程序都需要决定要“合并”多少级别的状态。默认值为 1 级。请阅读状态对账器文档以获取更多信息。

import { combineReducers, configureStore } from "@reduxjs/toolkit";
import logger from "redux-logger";
import usersReducer from "@/pages/users/usersSlice";
import postsReducer from "@/pages/posts/postsSlice";
import notificationsReducer from "@/pages/notifications/notificationsSlice";
import {persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER,} from "redux-persist"
import storage from "redux-persist/lib/storage"; // 默认为 localStorage

const isDev = import.meta.env.DEV;
export const rootReducer = combineReducers({
    users: usersReducer,
    posts: postsReducer,
    notifications: notificationsReducer,
});

const persistedReducer = persistReducer({ key: "root", storage }, rootReducer);

const store = configureStore({
    reducer: persistedReducer,
    devTools: isDev,
    middleware: getDefaultMiddleware => isDev ? getDefaultMiddleware({
        serializableCheck: {
            ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
        }
    }).concat(logger) : getDefaultMiddleware({
        serializableCheck: {
            ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
        }
    }),
})

export const persistor = persistStore(store);

export default store;

如果您使用的是react,请用 PersistPate 包装您的根组件。这会延迟应用程序 UI 的呈现,直到您的持久状态被检索并保存到 redux。注意:PersistPate 加载道具可以为空,也可以为任何反应实例,例如 loading={<loading/>}

API

persistReducer(config, reducer)

  • config:key, storage

  • blacklist:仅黑名单中的 reducer 不被存储

  • whitelist:仅存储白名单中的 reducer。

persistStore(store, [config, callback])

  • storeredux store 要持久化的存储。

  • config: object (通常为空),如果要避免在调用persistStore后立即启动持久性,请设置选项manualPersist。示例:{manualPersist: true}然后可以在任何时候使用 peristor.persist()启动持久性。如果在进行persistStore调用时您的存储尚未就绪,您通常希望这样做。

  • callback :函数将在 rehydration 完成后调用。

persistor

persistStore 使用以下方法返回 persistor 对象:

  • .purge():从磁盘中清除状态并返回 promise

  • .flush():立即将所有挂起状态写入磁盘并返回 promise

  • .pause(): 暂停持久性

  • .persist(): 恢复 persistence

黑名单和白名单

最后更新于