当前位置:   article > 正文

【React】redux数据持久化存储(react-redux、redux-RTK)_react存储数据

react存储数据

React】redux数据持久化存储(react-redux、redux-RTK)

1、下载依赖

npm i redux redux-persist 
  • 1

2、src/redux/index.jsx

import {configureStore} from "@reduxjs/toolkit";

import {userInfoReduce} from "./userInfoSlice.jsx";
import {globalReducer} from "./globalSlice.jsx";

import {combineReducers} from "redux";
import {persistReducer, persistStore} from 'redux-persist';
import storageSession  from 'redux-persist/lib/storage/session';  //sessionStorage
//import storageLocation  from 'redux-persist/lib/storage'; //存储到localStorage


const persistConfig = {
    key:'root',
    storage:storageSession,  //指定存储到session中
}

const persistedReducer = persistReducer(
    persistConfig,
    combineReducers({
        //数据切片
        userInfo:userInfoReduce,
        globalX:globalReducer
    })
)

export const store = configureStore({
    reducer:persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false,
        }),
})
export const persistor = persistStore(store)


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

3、src/main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'

import {Provider} from "react-redux";
import {store,persistor} from "./redux/index.jsx";
import {PersistGate} from "redux-persist/integration/react"

ReactDOM.createRoot(document.getElementById('root')).render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <App/>
        </PersistGate>
    </Provider>
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/510772
推荐阅读
相关标签
  

闽ICP备14008679号