在React項目中,我們經(jīng)常會通過redux以及react-redux來存儲和管理全局?jǐn)?shù)據(jù)。但是通過redux存儲全局?jǐn)?shù)據(jù)時,會有這么一個問題,如果用戶刷新了網(wǎng)頁,那么我們通過redux存儲的全局?jǐn)?shù)據(jù)就會被全部清空,比如登錄信息等。
這個時候,我們就會有全局?jǐn)?shù)據(jù)持久化存儲的需求。首先我們想到的就是localStorage,localStorage是沒有時間限制的數(shù)據(jù)存儲,我們可以通過它來實現(xiàn)數(shù)據(jù)的持久化存儲。
但是在我們已經(jīng)使用redux來管理和存儲全局?jǐn)?shù)據(jù)的基礎(chǔ)上,再去使用localStorage來讀寫數(shù)據(jù),這樣不僅是工作量巨大,還容易出錯。那么有沒有結(jié)合redux來達(dá)到持久數(shù)據(jù)存儲功能的框架呢?當(dāng)然,它就是redux-persist。redux-persist會將redux的store中的數(shù)據(jù)緩存到瀏覽器的localStorage中。
redux-persist的使用
1、對于reducer和action的處理不變,只需修改store的生成代碼,修改如下
import {createStore} from 'redux'import reducers from '../reducers/index'import {persistStore, persistReducer} from 'redux-persist';import storage from 'redux-persist/lib/storage';import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';const persistConfig = { key: 'root', storage: storage, stateReconciler: autoMergeLevel2 // 查看 'Merge Process' 部分的具體情況};const myPersistReducer = persistReducer(persistConfig, reducers)const store = createStore(myPersistReducer)export const persistor = persistStore(store)export default store2、在index.js中,將PersistGate標(biāo)簽作為網(wǎng)頁內(nèi)容的父標(biāo)簽
import React from 'react';import ReactDOM from 'react-dom';import {Provider} from 'react-redux'import store from './redux/store/store'import {persistor} from './redux/store/store'import {PersistGate} from 'redux-persist/lib/integration/react';ReactDOM.render(<Provider store={store}>   <PersistGate loading={null} persistor={persistor}>    {/*網(wǎng)頁內(nèi)容*/}   </PersistGate>  </Provider>, document.getElementById('root'));這就完成了通過redux-persist實現(xiàn)React持久化本地數(shù)據(jù)存儲的簡單應(yīng)用
3、最后我們調(diào)試查看瀏覽器中的localStorage緩存數(shù)據(jù)

發(fā)現(xiàn)數(shù)據(jù)已經(jīng)存儲到了localStorage中,此時刷新網(wǎng)頁,redux中的數(shù)據(jù)也不會丟失
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答