redux-persist做用是将store中的数据缓存到浏览器中,减小数据请求,每当白名单中的数据发生变化,才会进行一次更新缓存的操做,而且这个数据缓存是存在localStorage中的,不是会话级别的缓存。react
安装方式两种:npm install --save redux-persist / yarn add redux-persistnpm
实现方式主要是依靠两个方法:persistStore和persistReducer,使用persistReducer时须要指定persistConfig,这一项就是你须要缓存的数据处理项,它有着黑白名单的处理方式,还须要一个storage的协助:redux
1 import {persistStore, persistReducer} from 'redux-persist'; 2 3 import storage from 'redux-persist/lib/storage'; 4 5 // BLACKLIST 6 const persistConfig = { 7 key: 'root', // key是放入localStorage中的key 8 storage: storage, // storage简单就能够理解成localStorage的功能封装吧,不过有时候因为版本问题,必要在后一个storage上加一个default属性,能够在console中打出来判断是否须要加 9 blacklist: ['navigation'] // navigation不会被存入缓存中,其余会,适用于少部分数据须要实时更新 10 }; 11 12 // WHITELIST 13 const persistConfig = { 14 key: 'root', 15 storage: storage, 16 whitelist: ['navigation'] // navigation会存入缓存,其余不会存,适用于大多数数据并不会实时从后台拿数据 17 };
而后在处理reducer时用到persistReducer,一种是直接使用,另外一种你可能会使用到combineReducers,接下来就是建立store了,可能会用到中间件,不过此时不要理睬中间件建立store的过程,期间和你以前的建立方式同样,在store建立好的外边,加一句话,而后export里包含persistor就好:浏览器
1 const reducers = persistReducer(persistConfig, reducer); 2 3 const reducers = combineReducers({ 4 depReducer: persistReducer(persistConfig, depReducer) 5 }); 6 const persistor = persistStore(store);
最后在ReactDOM.render()的时候引入另外一个组件:缓存
1 import {PersistGate} from 'redux-persist/lib/integration/react'; 2 3 ReactDOM.render( 4 <Provider store={store}> 5 <PersistGate persistor={persistor}> 6 <Dep /> 7 </PersistGate> 8 </Provider>, 9 document.getElementById('app') 10 );