当前位置: 首页 > article >正文

【React】react-redux+redux-toolkit实现状态管理

安装

npm install @reduxjs/toolkit react-redux
  1. Redux Toolkit 是官方推荐编写Redux的逻辑方式,用于简化书写方式
  2. React-redux 用来链接Redux和React组件之间的中间件

使用

定义数据

创建要管理的数据模块 store/module/counter.ts

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

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    counter: 0, // 初始值
  },
  reducers: {
  // 修改值的方法
    changeCounter: (state, { payload }: PayloadAction<number>) => {
      state.counter = payload // 使传入的参数赋值到counter
    },
  }
})

export const { changeCounter } = counterSlice.actions // 导出修改的方法
export default counterSlice.reducer

创建store/index.ts用于管理和导出项目所含的状态数据

import { configureStore } from '@reduxjs/toolkit'
import { useSelector, useDispatch } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'
import counterReducer from './module/counter' // 管理的模块

const store = configureStore({
	reducer:{
		counter: counterReducer // 定义管理的模块
	}
})

type RootState = ReturnType<typeof store.getState>
type AppDispatch = typeof store.dispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector // 导出使用数据的方法
export const useAppDispatch: () => AppDispatch = useDispatch // 导出修改数据的方法
export default store

为React注入store

在项目主入口main.tsx中, 使用Provider标签包裹来注入store

import { Provider } from "react-redux";
import store from "@/store/index.ts";

createRoot(document.getElementById("root") as HTMLElement).render(
  <Provider store={store}>
      <App />
  </Provider>
);

页面中使用/修改数据

import { useAppSelector, useAppDispatch } from "@/store";
import { changeCounter } from "@/store/module/counter";

const { count, text } = useAppSelector((state) => ({
	count: state.counter.counter, // 取值
}));

// 修改方法
const dispatch = useAppDispatch();
function handlecChangeCount() {
	dispatch(changeCounter(count + 1));
}

return (
    <>
        <div>{count}</div>
        <button onClick={handlecChangeCount}>change</button>
    </>
  );

http://www.kler.cn/a/545304.html

相关文章:

  • 基于WebAssembly的后端服务突破:打造高性能、安全的新型微服务架构
  • 27、深度学习-自学之路-NLP自然语言处理-做一个简单的项目识别一组电影评论,来判断电影评论是积极的,还是消极的。
  • Golang 进阶训练营
  • Rocky Linux系统修改网卡全攻略
  • 【清晰教程】本地部署DeepSeek-r1模型
  • C语言插入排序之直接插入排序
  • 【网络安全 | 漏洞挖掘】价值3133美元的Google IDOR
  • VS Code 通知中一直显示“Reactivating terminals...”的问题解决
  • 解决 paddle ocr 遇到 CXXABI_1.3.13 not found 的问题
  • JAVA DDD设计模式:用策略模式干掉满屏if-else
  • 吉祥汽车泰国首发,用 Unity 实现行业首创全 3D 座舱虚拟世界
  • 【深度学习】计算机视觉(CV)-目标检测-SSD(Single Shot MultiBox Detector)—— 单次检测多框检测器
  • 了解卷积神经网络(Convolutional Neural Network,CNN)
  • React组件重新渲染机制
  • App UI自动化--Appium学习--第二篇
  • 【Elasticsearch】标准化器(Normalizers)
  • Excel文件的读取
  • 【工业场景】用YOLOv8实现火灾识别
  • Windows软件自动化利器:pywinauto python
  • python 大数据的优势