Redux-persist使用

时间:2022-07-19 06:54:29

redux-persist作用是将store中的数据缓存到浏览器中,减少数据请求,每当白名单中的数据发生变化,才会进行一次更新缓存的操作,并且这个数据缓存是存在localStorage中的,不是会话级别的缓存。

安装方式两种:npm install --save redux-persist / yarn add redux-persist

实现方式主要是依靠两个方法:persistStore和persistReducer,使用persistReducer时需要指定persistConfig,这一项就是你需要缓存的数据处理项,它有着黑白名单的处理方式,还需要一个storage的协助:

 import {persistStore, persistReducer} from 'redux-persist';

 import storage from 'redux-persist/lib/storage';

 // BLACKLIST
const persistConfig = {
key: 'root', // key是放入localStorage中的key
storage: storage, // storage简单就可以理解成localStorage的功能封装吧,不过有时候由于版本问题,必要在后一个storage上加一个default属性,可以在console中打出来判断是否需要加
blacklist: ['navigation'] // navigation不会被存入缓存中,其他会,适用于少部分数据需要实时更新
}; // WHITELIST
const persistConfig = {
key: 'root',
storage: storage,
whitelist: ['navigation'] // navigation会存入缓存,其他不会存,适用于大多数数据并不会实时从后台拿数据
};

然后在处理reducer时用到persistReducer,一种是直接使用,另一种你可能会使用到combineReducers,接下来就是创建store了,可能会用到中间件,不过此时不要理睬中间件创建store的过程,期间和你之前的创建方式一样,在store创建好的外边,加一句话,然后export里包含persistor就好:

 const reducers = persistReducer(persistConfig, reducer);

 const reducers = combineReducers({
depReducer: persistReducer(persistConfig, depReducer)
});
const persistor = persistStore(store);

最后在ReactDOM.render()的时候引入另一个组件:

 import {PersistGate} from 'redux-persist/lib/integration/react';

 ReactDOM.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<Dep />
</PersistGate>
</Provider>,
document.getElementById('app')
);