react中使用redux-persist做持久化儲存的過程記錄
react中使用redux-persist做持久化儲存
某天下午折騰著玩的 – 筆記
安裝相關(guān)依賴
npm install @reduxjs/toolkit redux-persist redux react-redux
// store.jsx import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit"; import { persistStore, persistReducer } from "redux-persist"; import storage from "redux-persist/lib/storage"; // 選擇持久化存儲引擎,如 localStorage 或 AsyncStorage import rootReducer from "./reducers/index"; // 導(dǎo)入您的根 reducer // 配置持久化設(shè)置 const persistConfig = { key: "root", // 存儲的鍵名 storage, // 持久化存儲引擎 // 可選的配置項(xiàng),如白名單、黑名單等 選其一就好了 // blacklist:['test'], // 只有 test 不會被緩存 // whitelist: ["test"], // 只有 test 會被緩存 }; const persistedReducer = persistReducer(persistConfig, rootReducer); const store = configureStore({ reducer: persistedReducer, middleware: getDefaultMiddleware({ serializableCheck: false, // 禁用嚴(yán)格模式 }), }); const persistor = persistStore(store); export { store, persistor };
將 store 提供給應(yīng)用程序:將 Redux store 提供給根組件,以便在整個應(yīng)用程序中可以訪問到 Redux 狀態(tài)
// main.jsx import React from "react"; import ReactDOM from "react-dom/client"; import { Provider } from "react-redux"; import { PersistGate } from "redux-persist/integration/react"; import { store, persistor } from "./redux/store"; import App from "./App"; ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <App /> </PersistGate> </Provider> </React.StrictMode> );
reducer 示例:
// reducers/index.jsx import { combineReducers } from "redux"; import userReducer from "./user"; import baseReducer from "./base"; const rootReducer = combineReducers({ user: userReducer, base: baseReducer, }); export default rootReducer;
// reducers/user.jsx import { createSlice } from "@reduxjs/toolkit"; const initialState = { token: "默認(rèn)值token", isLogin: false, }; const user = createSlice({ name: "user", initialState, reducers: { setToken: (state, action) => { // 將傳入的值設(shè)置為 token 的新值 state.token = action.payload; }, }, }); export const { setToken } = user.actions; export default user.reducer;
在組件中使用
// App.jsx import { useSelector, useDispatch } from "react-redux"; import { setToken } from "./redux/reducers/user"; const App = () => { const user = useSelector((state) => state.user); // 在頁面組件中使用 useDispatch 獲取 dispatch 函數(shù),用于派發(fā) action const dispatch = useDispatch(); const setTokenFun = () => { dispatch(setToken("一個新的token")); }; return ( <> <p>token=====:{user.token}</p> <Button type="primary" onClick={setAddressFun}> Set Token </Button> </> ); }; export default App;
補(bǔ)充:React-persist的使用(數(shù)據(jù)持久化)
在React項(xiàng)目中,我們經(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ù)存儲,我們可以通過它來實(shí)現(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中。
一、安裝
$ npm install redux-persist --save
二、使用
/* 該文件專門用于暴露一個store對象,整個應(yīng)用只有一個store對象 */ //引入createStore,專門用于創(chuàng)建redux中最為核心的store對象 import { createStore, applyMiddleware ,combineReducers} from 'redux' //引入redux-persist持久化 import { persistStore, persistReducer } from 'redux-persist' // import localStorage from 'redux-persist/lib/storage' import storage from 'redux-persist/lib/storage/index' //引入為Count組件服務(wù)的reducer import incrementReducer from './incrementReducer'; import personReducer from './personReducer'; //引入中間件 可傳入action為函數(shù) import thunk from 'redux-thunk'; // 引入redux-devtools-extension 第三方可視化redux的工具 import {composeWithDevTools} from 'redux-devtools-extension' // import {composeWithDevTools} from 'redux-devtools-extension' //實(shí)現(xiàn)persist數(shù)據(jù)持久化 const config = { key: 'root', storage:storage, //引入的storage是存在local或session } //里面保存的是redux完整的key和value 在mapStateToProps調(diào)動key const allReducer = combineReducers({ incrementReducer, personReducer }) const store = createStore(persistReducer(config,allReducer),composeWithDevTools(applyMiddleware(thunk))) persistStore(store) export default store //正常版暴露store,thunk是保證action可以接收函數(shù) // export default createStore(reducer, applyMiddleware(thunk))
對于reducer和action的處理不變,只需修改store的生成代碼
到此這篇關(guān)于react中使用redux-persist做持久化儲存的文章就介紹到這了,更多相關(guān)react redux-persis持久化儲存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React?Native性能優(yōu)化指南及問題小結(jié)
本文將介紹在React?Native開發(fā)中常見的性能優(yōu)化問題和解決方案,包括ScrollView內(nèi)無法滑動、熱更新導(dǎo)致的文件引用問題、高度獲取、強(qiáng)制橫屏UI適配、低版本RN適配iOS14、緩存清理、navigation參數(shù)取值等,感興趣的朋友一起看看吧2024-01-01React 使用browserHistory項(xiàng)目訪問404問題解決
這篇文章主要介紹了React 使用browserHistory項(xiàng)目訪問404問題解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06React實(shí)現(xiàn)多標(biāo)簽在有限空間內(nèi)展示
在業(yè)務(wù)中,需要在一個卡片組件中展示多個標(biāo)簽,標(biāo)簽組件高度相同,寬度和出現(xiàn)順序不同,要求標(biāo)簽只能在有限的空間內(nèi)展示,所以本文給大家介紹了React實(shí)現(xiàn)多標(biāo)簽在有限空間內(nèi)展示,需要的朋友可以參考下2023-12-12React創(chuàng)建對話框組件的方法實(shí)例
在項(xiàng)目開發(fā)過程中,對于復(fù)雜的業(yè)務(wù)選擇功能很常見,下面這篇文章主要給大家介紹了關(guān)于React創(chuàng)建對話框組件的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05