React+Redux 数据存储持久化

React+Redux 数据存储持久化

1、安装相关依赖

yarn add @reduxjs/toolkit redux react-redux redux-persist

2、userSlice:用户状态数据切片封装

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IUserInfo {
  userName: string
  avatar?: string
  brief?: string
}

// 使用该类型定义初始 state
const initialState = {
  userInfo: <IUserInfo>{
    userName: 'zh',
    brief: '无心'
  }
}

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // action: {
    //   payload: { uerName: 'zhw' },
    //   type: 'user/updateUserName'    name + 方法名
    // }
    // 使用: dispatch(updateUserName({ uerName: 'zhw' }))
    // // 使用 PayloadAction 类型声明 `action.payload` 的内容
    updateUserInfo: (state, action: PayloadAction<IUserInfo>) => {
      // Redux Toolkit 允许在 reducers 中编写 "mutating" 逻辑。
      // 它实际上并没有改变 state,因为使用的是 Immer 库,检测到“草稿 state”的变化并产生一个全新的
      // 基于这些更改的不可变的 state。

      state.userInfo = action.payload
    }
  }
})

// 导出修改state  dispatch时的actions
export const { updateUserInfo } = userSlice.actions
export default userSlice.reducer

3、在store的index.ts中

默认已经模块化了reducers,如下图所示

在这里插入图片描述

// configureStore: store配置项
import { configureStore } from '@reduxjs/toolkit'
// combineReducers: 组合reducers目录下的所有reducer模块
import { combineReducers } from 'redux'
// 数据持久化
import { persistStore, persistReducer } from 'redux-persist'
// defaults to localStorage for web
import storageLocation from 'redux-persist/lib/storage' 
// import storageSession from 'redux-persist/lib/storage/session'

// 导入自己封装好的reducers
import userReducer from './reducers/userSlice'
// 持久化存储配置对象
const persistConfig = {
  key: 'root',
  version: 1,
  storage: storageLocation
}
// 持久化处理后的reducers
const persistedReducer = persistReducer(
  persistConfig,
  combineReducers({
    // 数据切片
    userReducer
  })
)
// 将初九话插件和store通过middleware关联起来
const store = configureStore({
  // userReducer 模块名
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false
    })
})

// 可以订阅 store
// store.subscribe(() => console.log(store.getState(), 'userSlice'))

// 持久化的store
const persistor = persistStore(store)

export { store, persistor }

4、将store和App组件关联起来

import React from 'react'
import ReactDOM from 'react-dom/client'
// UI css
// antd v5 自带的重置样式
import 'antd/dist/reset.css'
// 自定义css
import '@/assets/style/global.scss'

// 导入路由模式
import { BrowserRouter } from 'react-router-dom'
// 导入redux仓库
import { Provider } from 'react-redux'
import { store, persistor } from '@/store'
// store持久化
import { PersistGate } from 'redux-persist/integration/react'

import App from './App.tsx'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <React.StrictMode>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </React.StrictMode>
    </PersistGate>
  </Provider

5、在组件中使用store

import { useSelector, useDispatch } from 'react-redux'
import { updateUserInfo } from '@/store/reducers/userSlice'
const Home = () => {
  const {
    userInfo: { userName, brief }
  } = useSelector((state: RootState) => state.userReducer)

  const dispatch = useDispatch()
  const test = () => {
    dispatch(updateUserInfo({ userName: 'zhw', brief: '那就这样吧' }))
  }
  return (
    <>
      <div>home page</div>
      <p>{userName}</p>
      <p>{brief}</p>
      <button onClick={test}>测试</button>
    </>
  )
}
export default Home

数据持续化存储github redux-persist
redux工具redux RTK

redux官网 redux

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React Redux中实现数据持久有多种方法,下面是其中一种常用的方法: 1. 使用redux-persist库:redux-persist是一个用于实现Redux数据持久的第三方库。它通过将Redux store中的数据保存到本地存储(如localStorage或sessionStorage)中,以便在刷新页面或重新加载应用程序时保持数据持久性。 首先,安装redux-persist库: ``` npm install redux-persist ``` 然后,在Redux的配置文件中,进行redux-persist的配置和初始: ```javascript import { createStore } from 'redux'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // 默认使用localStorage // 导入你的reducer import rootReducer from './reducers'; // 配置redux-persist const persistConfig = { key: 'root', // 存储的key,默认为root storage, // 使用的存储引擎,默认为localStorage }; const persistedReducer = persistReducer(persistConfig, rootReducer); // 创建store const store = createStore(persistedReducer); const persistor = persistStore(store); export { store, persistor }; ``` 最后,在应用程序的入口文件中,使用`PersistGate`组件包裹整个应用程序,并将`persistor`作为其属性: ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { PersistGate } from 'redux-persist/integration/react'; import { store, persistor } from './store'; ReactDOM.render( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> // 应用程序的根组件 </PersistGate> </Provider>, document.getElementById('root') ); ``` 使用以上配置,Redux的状态将会被自动保存到本地存储中,并在应用程序重新加载时被恢复。你可以根据需要自行调整配置,例如设置存储引擎、存储的key等。详细的配置和更多高级用法,请参考redux-persist库的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原谅我很悲

不要打赏哦,加个好友一起学习呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值