5分钟掌握React的Redux Toolkit + Redux

embedded/2025/2/5 16:41:57/

Redux Toolkit + Redux 教程

1. 引言

本教程介绍如何使用 Redux Toolkit(RTK)TypeScript 搭建 Redux 状态管理系统。
我们将创建一个 计数器(Counter)待办事项(Todo) 模块,并学习 Redux 的核心 API,如 createSliceconfigureStoreuseSelectoruseDispatch


2. 依赖安装

在 React 项目中安装 Redux Toolkit 和 React-Redux:

npm install @reduxjs/toolkit react-redux

如果使用 TypeScript,还需安装类型支持:

npm install -D @types/react-redux

3. 代码实现

3.1 定义 State 类型

// 定义 Counter 组件的状态类型
interface CounterState {value: numbertitle: string    // 添加一个新字段,展示更多状态管理
}// 定义初始状态
const initialState: CounterState = {value: 0,title: "计数器"
};

3.2 创建多个 Slice

Redux Toolkit 通过 createSlice 简化了 Redux 的 reduceraction 创建。

创建 counterSlice
import { createSlice, PayloadAction } from "@reduxjs/toolkit";const counterSlice = createSlice({name: "counter",  // Slice 名称initialState,     // 初始状态reducers: {increment: (state, action: PayloadAction<number>) => {state.value += action.payload;},decrement: (state, action: PayloadAction<number>) => {state.value -= action.payload;},reset: (state) => {state.value = 0;},setTitle: (state, action: PayloadAction<string>) => {state.title = action.payload;},incrementAndSetTitle: (state, action: PayloadAction<{ amount: number; title: string }>) => {state.value += action.payload.amount;state.title = action.payload.title;}}
});
创建 todoSlice
const todoSlice = createSlice({name: "todos",  // 不同的 SliceinitialState: { items: [] },reducers: {addTodo: (state, action) => {state.items.push(action.payload);}}
});

3.3 创建 Redux Store

import { configureStore } from "@reduxjs/toolkit";const store = configureStore({reducer: {counter: counterSlice.reducer,todos: todoSlice.reducer}
});export default store;

📌 Redux Toolkit 默认启用了 Redux DevTools 和 Redux Thunk,简化了开发流程。


3.4 导出 Action Creators

const { decrement } = counterSlice.actions;
const { addTodo } = todoSlice.actions;

3.5 创建 Redux 类型

// 从 store 推导出 RootState 类型
export type RootState = ReturnType<typeof store.getState>;
// 推导出 dispatch 类型
export type AppDispatch = typeof store.dispatch;

这样可以在 useSelectoruseDispatch 中提供正确的类型支持。


3.6 创建 Counter 组件

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "./store";
import { increment, decrement, reset, setTitle, incrementAndSetTitle, addTodo } from "./store";const Counter = () => {const count = useSelector((state: RootState) => state.counter.value);const title = useSelector((state: RootState) => state.counter.title);const dispatch = useDispatch();return (<div><h2>{title}: {count}</h2><div>{/* 触发状态更新 */}<button onClick={() => dispatch(increment(1))}>+1</button><button onClick={() => dispatch(increment(5))}>+5</button><button onClick={() => dispatch(decrement(1))}>-1</button><button onClick={() => dispatch(decrement(5))}>-5</button><button onClick={() => dispatch(reset())}>重置</button>{/* 修改标题 */}<input value={title}onChange={(e) => dispatch(setTitle(e.target.value))}placeholder="输入新标题"/>{/* 组合 action */}<button onClick={() => dispatch(incrementAndSetTitle({ amount: 10, title: "增加了10!" }))}>增加10并更新标题</button>{/* 添加任务 */}<button onClick={() => dispatch(addTodo("新任务"))}>添加任务</button></div></div>);
};

3.7 创建根组件

import { Provider } from "react-redux";
import store from "./store";
import Counter from "./Counter";export const CounterApp = () => {return (<Provider store={store}><Counter /></Provider>);
};

4. 总结

  • createSlice:定义 reduceraction creators
  • configureStore:创建 store 并自动配置 Redux DevToolsRedux Thunk
  • useSelector:从 store 读取状态。
  • useDispatch:分发 action 进行状态更新。

📌 通过 Redux Toolkit,我们大大简化了 Redux 的使用,让代码更加简洁、高效!


http://www.ppmy.cn/embedded/159798.html

相关文章

Java项目: 基于SpringBoot+mybatis+maven+mysql实现的疫苗发布和接种预约管理系统(含源码+数据库+开题报告+毕业论文)

一、项目简介 本项目是一套基于SpringBootmybatismavenmysql疫苗发布和接种预约管理系统 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;eclipse或者idea 确保可以运行&#xff01; 该系统功能完善、…

第四章:玄丹-React商品管理实战

https://ant-design.antgroup.com/components/table-cn 在这里找到我们的 Table 表格,来完成我们的商品功能实战,下面我们会学到 表格类组件的渲染表格函数组件的渲染图片上传组件弹窗组件按钮组件axios 工具的封装分页功能的实现商品管理基础表格 import React from react;…

一个开源 GenBI AI 本地代理(确保本地数据安全),使数据驱动型团队能够与其数据进行互动,生成文本到 SQL、图表、电子表格、报告和 BI

一、GenBI AI 代理介绍&#xff08;文末提供下载&#xff09; github地址&#xff1a;https://github.com/Canner/WrenAI 本文信息图片均来源于github作者主页 在 Wren AI&#xff0c;我们的使命是通过生成式商业智能 &#xff08;GenBI&#xff09; 使组织能够无缝访问数据&…

C++继承的基本意义

文章目录 一、继承的本质和原理二、重载、隐藏和覆盖三、基类与派生类的转换 一、继承的本质和原理 继承的本质&#xff1a;a. 代码的复用 b. 类和类之间的关系&#xff1a; 组合&#xff1a;a part of… 一部分的关系 继承&#xff1a;a kind of… 一种的关系 总结&#xff…

list的使用,及部分功能的模拟实现(C++)

目录&#xff08;文章中"节点"和"结点"是同一个意思&#xff09; 1. list的介绍及使用 1.1 list的介绍 1.2 list的使用 1.2.1 list的构造 1.2.2 list iterator的使用 1.2.3 list capacity 1.2.4 list element access 1.2.5 list modifiers 1.2.6 list…

开源AI智能名片2+1链动模式S2B2C商城小程序:重塑私域流量运营格局

摘要&#xff1a;本文深入探讨互联网行业流量接纳方式从百度搜索到微信号营销的演变历程&#xff0c;详细剖析个人微信号作为私域流量核心载体的运营要点。同时&#xff0c;全面引入开源AI智能名片2 1链动模式S2B2C商城小程序这一创新工具&#xff0c;深入研究其功能特性、创新…

PyDeequ库在AWS EMR启动集群中数据质量检查功能的配置方法和实现代码

PyDeequ是一个基于Apache Spark的Python API&#xff0c;专门用于定义和执行“数据单元测试”&#xff0c;从而在大规模数据集中测量数据质量。 PyDeequ框架在PySpark代码中提供了全面的数据质量检查功能&#xff0c;能够帮助用户&有效地监控和提升大规模数据集的数据质量。…

基于微信小程序的绘画学习平台的设计与开发

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…