欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react中使用redux-persist做持久化儲存的過程記錄

 更新時間:2024年01月17日 14:59:00   作者:WeirdoPrincess  
這篇文章主要介紹了react中使用redux-persist做持久化儲存的相關(guān)資料,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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)文章

  • 2個奇怪的react寫法

    2個奇怪的react寫法

    大家好,我卡頌。雖然React官網(wǎng)用大量篇幅介紹最佳實(shí)踐,但因JSX語法的靈活性,所以總是會出現(xiàn)奇奇怪怪的React寫法。本文介紹2種奇怪(但在某些場景下有意義)的React寫法。也歡迎大家在評論區(qū)討論你遇到過的奇怪寫法
    2023-03-03
  • React?Native性能優(yōu)化指南及問題小結(jié)

    React?Native性能優(yōu)化指南及問題小結(jié)

    本文將介紹在React?Native開發(fā)中常見的性能優(yōu)化問題和解決方案,包括ScrollView內(nèi)無法滑動、熱更新導(dǎo)致的文件引用問題、高度獲取、強(qiáng)制橫屏UI適配、低版本RN適配iOS14、緩存清理、navigation參數(shù)取值等,感興趣的朋友一起看看吧
    2024-01-01
  • React 使用browserHistory項(xiàng)目訪問404問題解決

    React 使用browserHistory項(xiàng)目訪問404問題解決

    這篇文章主要介紹了React 使用browserHistory項(xiàng)目訪問404問題解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • ReactJS中使用TypeScript的方法

    ReactJS中使用TypeScript的方法

    TypeScript 實(shí)際上就是具有強(qiáng)類型的 JavaScript,可以對類型進(jìn)行強(qiáng)校驗(yàn),好處是代碼閱讀起來比較清晰,代碼類型出現(xiàn)問題時,在編譯時就可以發(fā)現(xiàn),而不會在運(yùn)行時由于類型的錯誤而導(dǎo)致報(bào)錯,這篇文章主要介紹了ReactJS中使用TypeScript的方法,需要的朋友可以參考下
    2024-04-04
  • React Native功能豐富的Toast通知庫

    React Native功能豐富的Toast通知庫

    這篇文章主要為大家介紹了React Native功能豐富的Toast通知庫使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • React Native 截屏組件的示例代碼

    React Native 截屏組件的示例代碼

    本篇文章主要介紹了React Native 截屏組件的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • react無限滾動組件的實(shí)現(xiàn)示例

    react無限滾動組件的實(shí)現(xiàn)示例

    本文主要介紹了react無限滾動組件的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • React實(shí)現(xiàn)多標(biāo)簽在有限空間內(nèi)展示

    React實(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-12
  • react-router?v6新特性總結(jié)示例詳解

    react-router?v6新特性總結(jié)示例詳解

    在V6版本中,<Switch>組件被替換成<Routes>組件,同時,component屬性被element屬性替換,這篇文章主要介紹了react-router?v6新特性總結(jié),需要的朋友可以參考下
    2022-12-12
  • React創(chuàng)建對話框組件的方法實(shí)例

    React創(chuàng)建對話框組件的方法實(shí)例

    在項(xiàng)目開發(fā)過程中,對于復(fù)雜的業(yè)務(wù)選擇功能很常見,下面這篇文章主要給大家介紹了關(guān)于React創(chuàng)建對話框組件的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-05-05

最新評論