当前位置:   article > 正文

React Store及store持久化的使用_react store 数据持久化

react store 数据持久化

1.安装

  1. npm insatll react-redux
  2. npm install @reduxjs/toolkit
  3. npm install redux-persist

2. 使用React Toolkit创建counterStore并配置持久化

store/modules/counterStore.ts:

  1. import { createSlice } from '@reduxjs/toolkit'
  2. // 定义状态类型
  3. interface Action {
  4. payload:number,
  5. type: string
  6. }
  7. interface State {
  8. count: number
  9. }
  10. export const counterStore = createSlice({
  11. // 模块名称独一无二
  12. name: 'counter',
  13. // 初始数据
  14. initialState: {
  15. count: 1
  16. },
  17. // 修改数据的同步方法
  18. reducers: {
  19. increment: (state:State) => {
  20. state.count += 1
  21. },
  22. decrement: (state:State) => {
  23. state.count -= 1
  24. },
  25. incrementNum: (state:State, action: Action) => {
  26. state.count += action.payload
  27. }
  28. }
  29. })
  30. // 导出
  31. export const { increment, decrement, incrementNum } = counterStore.actions
  32. export default counterStore.reducer

store/index.ts:

  1. import { configureStore, combineReducers } from '@reduxjs/toolkit'
  2. import counterReducer from './modules/counterStore'
  3. import { persistStore, persistReducer } from 'redux-persist'
  4. // 选择持久化存储引擎,如 localStorage 或 AsyncStorage
  5. import storage from 'redux-persist/lib/storage' // 默认使用localStorage作为存储引擎
  6. // 组合各个模块的reducer
  7. const reducer = combineReducers({
  8. counter: counterReducer
  9. })
  10. // 配置持久化设置
  11. const persistConfig = {
  12. key: 'root', // 存储的键名
  13. storage // 持久化存储引擎
  14. // 可选的配置项,如白名单、黑名单等 选其一就好了
  15. // blacklist:['test'], // 只有 test 不会被缓存
  16. // whitelist: ["test"], // 只有 test 会被缓存
  17. }
  18. const persistedReducer = persistReducer(persistConfig, reducer)
  19. export const store = configureStore({
  20. reducer: persistedReducer, // 注册子模块
  21. middleware: (getDefaultMiddleware) =>
  22. getDefaultMiddleware({
  23. serializableCheck: false // 关闭默认的序列化检查//关闭严格模式
  24. })
  25. })
  26. export const persistor = persistStore(store)

 

 3. 为React注入store

react-redux负责把Redux和React 链接 起来,内置 Provider组件,通过 store 参数把创建好的store实例注入到应用中,链接正式建立

main.tsx:

  1. import ReactDOM from 'react-dom/client'
  2. import App from './App'
  3. import { BrowserRouter } from "react-router-dom"
  4. import { Provider } from 'react-redux'
  5. import {store, persistor } from "@/store"
  6. // store持久化
  7. import { PersistGate } from 'redux-persist/integration/react'
  8. ReactDOM.createRoot(document.getElementById('root')!).render(
  9. <Provider store={store}>
  10. {/* 注入router实例 */}
  11. <BrowserRouter>
  12. <PersistGate loading={null} persistor={persistor}>
  13. <App />
  14. </PersistGate>
  15. </BrowserRouter>
  16. </Provider>
  17. )

4. React组件使用store中的数据

useSelector,作用:在函数组件中获取redux数据存储对象中的某个数据

useDispatch,作用: 在函数组件中获取dipatch方法(用于发送action给reducer函数)

  1. import React from "react";
  2. import { useDispatch,useSelector } from "react-redux";
  3. import { increment, decrement, incrementNum } from '@/store/modules/counterStore'
  4. const App: React.FC = () => {
  5. const dispatch = useDispatch()
  6. const { count } = useSelector((state:any) => state.counter)
  7. return (
  8. <div>
  9. <div>{count}</div>
  10. <button onClick={() => {dispatch(increment())}}>加1</button>
  11. <button onClick={() => {dispatch(decrement())}}>减1</button>
  12. <button onClick={() => {dispatch(incrementNum(5))}}>加5</button>
  13. </div>
  14. );
  15. };
  16. export default App;

这样刷新之后数据就不会初始化了 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/510771
推荐阅读
相关标签
  

闽ICP备14008679号