React Store及store持久化的使用

React Store及store持久化的使用_第1张图片

1.安装

npm insatll react-redux
npm install @reduxjs/toolkit
npm install redux-persist

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

React Store及store持久化的使用_第2张图片

store/modules/counterStore.ts:

import { createSlice } from '@reduxjs/toolkit'

// 定义状态类型  
interface Action {  
  payload:number,
  type: string
} 
interface State {  
  count: number
} 

export const counterStore = createSlice({
  // 模块名称独一无二
  name: 'counter',
  // 初始数据
  initialState: {
    count: 1
  },
  // 修改数据的同步方法
  reducers: {
		increment: (state:State) => {
      state.count += 1
    },
    decrement: (state:State) => {
      state.count -= 1
    },
    incrementNum: (state:State, action: Action) => {
      state.count += action.payload
    }
  }
})

// 导出
export const { increment, decrement, incrementNum } = counterStore.actions
export default counterStore.reducer

store/index.ts:

import { configureStore, combineReducers } from '@reduxjs/toolkit'
import counterReducer from './modules/counterStore'

import { persistStore, persistReducer } from 'redux-persist'
// 选择持久化存储引擎,如 localStorage 或 AsyncStorage
import storage from 'redux-persist/lib/storage' // 默认使用localStorage作为存储引擎

// 组合各个模块的reducer
const reducer = combineReducers({
  counter: counterReducer
})

// 配置持久化设置
const persistConfig = {
  key: 'root', // 存储的键名
  storage // 持久化存储引擎
  // 可选的配置项,如白名单、黑名单等 选其一就好了
  // blacklist:['test'], // 只有 test 不会被缓存
  // whitelist: ["test"], // 只有 test 会被缓存
}

const persistedReducer = persistReducer(persistConfig, reducer)

export const store = configureStore({
  reducer: persistedReducer, // 注册子模块
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false // 关闭默认的序列化检查//关闭严格模式
    })
})

export const persistor = persistStore(store)

React Store及store持久化的使用_第3张图片 

 3. 为React注入store

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

main.tsx:

import ReactDOM from 'react-dom/client'
import App from './App'
import { BrowserRouter } from "react-router-dom"
import { Provider } from 'react-redux'
import {store, persistor } from "@/store"
// store持久化
import { PersistGate } from 'redux-persist/integration/react'

ReactDOM.createRoot(document.getElementById('root')!).render(
  
    {/* 注入router实例 */}
    
      
        
      
    
  
)

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

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

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

import React from "react";
import { useDispatch,useSelector } from "react-redux";
import { increment, decrement, incrementNum } from '@/store/modules/counterStore'

const App: React.FC = () => {
  const dispatch = useDispatch()

  const { count } = useSelector((state:any) => state.counter)
  return (
    
{count}
); }; export default App;

React Store及store持久化的使用_第4张图片

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

你可能感兴趣的:(react,react.js,前端,前端框架)