Redux-persist使用


  redux-persist作用是將store中的數據緩存到瀏覽器中,減少數據請求,每當白名單中的數據發生變化,才會進行一次更新緩存的操作,並且這個數據緩存是存在localStorage中的,不是會話級別的緩存。

  安裝方式兩種:npm install --save redux-persist / yarn add redux-persist

  實現方式主要是依靠兩個方法:persistStore和persistReducer,使用persistReducer時需要指定persistConfig,這一項就是你需要緩存的數據處理項,它有着黑白名單的處理方式,還需要一個storage的協助:

 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 );


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM