redux-persist
2021-03-12 本文已影响0人
金樽明月
基础使用
牵扯到 persistStore
persistReducer
两个 API。
// configureStore.js
import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import rootReducer from './reducers'
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
return { store, persistor }
}
persistStore 用来生产 persistor 的 store,是必须配置的。 persistReducer 不是必须的,而且可以对包含任意 reducer ,实现精确控制需要 persist 的内容。
import { PersistGate } from 'redux-persist/integration/react'
// ... normal setup, create store and persistor, import components etc.
const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};
以上是 react app 的使用实例,