redux-persist README

项目的 README,来自 github.com/endograph/redux-persist。合并为一个 markdown 文件:README.md。

redux-persist

Quickstart · API · Storage engines · npm

redux-persist

CI npm npm next downloads license

Persist and rehydrate a redux store. Your state is saved to storage as it changes and restored into the store when your app starts.

Hey all! redux-persist is maintained again, and v7 is in beta (npm install redux-persist@next): Redux Toolkit 2 support with no extra setup, a fix for stored data getting wiped (#809), and lots more. Please try it and tell us how it goes in the v7 beta discussion.

These docs are for v7, which needs Redux 5 or Redux Toolkit 2. Upgrading from 6? Read the migration guide; your stored data carries over as is. For 6.x, see the v6 docs.

Quickstart

npm install redux-persist

Wrap your root reducer and create a persistor alongside the store:

// app/store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/storage' // localStorage on the web
import userReducer from './features/user/userSlice'
import configReducer from './features/config/configSlice'

const rootReducer = combineReducers({
  user: userReducer,
  config: configReducer
})

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
  reducer: persistedReducer,
})

export const persistor = persistStore(store)

If you use React, wrap your root component in PersistGate. It holds off rendering until the stored state has been loaded back into redux. loading can be null or any React element, e.g. loading={<Loading />}.

import { PersistGate } from 'redux-persist/react'
import { store, persistor } from './app/store'

// ... normal setup, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};

If you'd rather not gate rendering, useRehydrated(persistor) from redux-persist/react returns whether stored state has loaded.

Every app has to decide how many levels of stored state to merge into its initial state. The default is one level; read state reconcilers before you ship.

React Native

Pass your storage engine explicitly:

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

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
}

Server rendering

redux-persist/storage works during server rendering (Next.js and others): on the server it stores nothing, and stored state is loaded in the browser. With the Next.js App Router, render PersistGate from a Client Component; see PersistGate.

Choosing what's saved

denylist and allowlist pick top-level keys:

persistReducer({ key: 'root', storage, denylist: ['navigation'] }, rootReducer) // navigation will not be persisted

persistReducer({ key: 'root', storage, allowlist: ['navigation'] }, rootReducer) // only navigation will be persisted

They're checked against your state's keys, so a typo is a type error. If you declare the config separately, annotate it with PersistConfig<RootState> or use as const on the array. The older names blacklist and whitelist still work.

For keys you can't list ahead of time, pass a function that's called with each top-level key:

persistReducer({ key: 'root', storage, denylist: key => key.startsWith('temp') }, rootReducer) // keys starting with temp will not be persisted

To go deeper than one level, use nested persists.

Resetting state on logout

Reset state inside the reducer you pass to persistReducer, so the reset state is saved too:

const rootReducer = (state, action) =>
  appReducer(action.type === 'user/logout' ? undefined : state, action)

const persistedReducer = persistReducer(persistConfig, rootReducer)

The reset state is saved like any other change. To write it right away (for example before the app might close), await persistor.flush() after dispatching the action.

Don't reset above persistReducer (by wrapping the persisted reducer, or with a store enhancer that replaces the whole state): that removes the _persist key, so the state stops being saved, and the previous user's state is loaded again on the next launch. redux-persist logs an error in development when this happens.

Learn more

Contributing

Bug reports and pull requests are welcome; see CONTRIBUTING.md, especially before changing anything that touches stored data. Questions and feature ideas go in Discussions. Feedback on the v7 beta goes in the v7 beta discussion.

redux-persist (endograph/redux-persist)

正在搜索数据库…

这是什么?Redux Persist 是一个库,可以把你的 Redux store 保存(持久化)到存储中,并在应用重新加载时自动恢复状态,这样页面刷新或应用重启后,状态也不会丢失。
它是要加到我现有 Redux 项目里的库,还是独立的工具?它是一个库,要安装到现有的 Redux 应用中;你需要用 persistReducer 包裹 reducer,并对 store 调用 persistStore。
我该怎么把它加到项目里?用 npm install redux-persist 安装;用 persistReducer(config, reducer) 包裹根 reducer,用 persistStore(store) 创建 persistor;如果需要,可以用 PersistGate 包裹你的 React 应用,让界面等状态恢复完成后再渲染。
我需要特定的存储引擎吗,还是开箱即用?它自带面向网页的 localStorage 和 sessionStorage 引擎,还支持大量社区存储引擎,比如 electron-store、react-native-fs、Expo 的 filesystem/SecureStore、通过 localForage 使用的 IndexedDB、PouchDB、Realm 等。你只需把它们传入配置即可。
设置时最需要注意的坑是什么?你必须选对状态协调器(reconciler),也就是决定恢复的持久化状态如何与 reducer 的初始状态合并。默认的合并方式只做一层的浅合并,如果不小心,嵌套的状态可能会被悄悄丢掉。
这个库只能用在 React 应用里吗?不是。核心库与框架无关,可以用于任何 Redux store(网页或 React Native);PersistGate 只是一个可选的、专为 React 设计的便捷组件。
我可以只持久化部分状态吗?可以。使用 whitelist/blacklist 配置项,可以包含或排除指定的 reducer 键;也可以嵌套更多层 persistReducer,实现更细粒度的控制。
数据结构变化时,怎么迁移已存储的状态?persistReducer 接受一个 migrate 函数,它会在状态合并前作用于加载的状态。redux-persist 还提供了 createMigrate,用来在不同版本的状态结构之间构建同步迁移。
能在保存数据前对其做处理吗,比如压缩或加密?可以。Transform(转换)允许你在状态持久化之前和恢复之后立即修改它;社区也有用于压缩(lz-string)、AES 加密以及筛选部分状态子集的包。
这个项目的维护情况怎么样了?2021 年 9 月,项目移交给了新的维护者,他正在梳理问题、升级依赖,并把代码库从 Flow 迁移到 TypeScript,从 Ava 迁移到 Jest。
作者
endograph
大小
1.4 MB
星标
13K
时长
11年
提交 · 90 天