Redux-persist使用
生活随笔
收集整理的這篇文章主要介紹了
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 );
總結
以上是生活随笔為你收集整理的Redux-persist使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 太空运行将近 40 年后,NASA 退役
- 下一篇: Eureka 介绍