5分钟掌握React的Redux Toolkit + Redux

devtools/2025/2/9 1:55:00/

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/devtools/157231.html

相关文章

C++六大默认成员函数

C六大默认成员函数 默认构造函数默认析构函数RAII技术RAII的核心思想优点示例应用场景 默认拷贝构造深拷贝和浅拷贝 默认拷贝赋值运算符移动构造函数&#xff08;C11起&#xff09;默认移动赋值运算符&#xff08;C11起&#xff09;取地址及const取地址操作符重载取地址操作符重…

QT +FFMPEG4.3 拉取 RTMP/http-flv 流播放 AVFrame转Qimage

QT FFMPEG4.3 拉取 RTMP/http-flv 流播放 Cc_Video_thread.h #ifndef CC_VIDEO_THREAD_H #define CC_VIDEO_THREAD_H#include <QThread> #include <QAtomicInt> #include <QImage>#ifdef __cplusplus extern "C" { #endif #include <libavfor…

C基础寒假练习(8)

一、终端输入10个学生成绩&#xff0c;使用冒泡排序对学生成绩从低到高排序 #include <stdio.h> int main(int argc, const char *argv[]) {int arr[10]; // 定义一个长度为10的整型数组&#xff0c;用于存储学生成绩int len sizeof(arr) / sizeof(arr[0]); // 计算数组…

DeepSeek 开源模型全解析(2024.1.1–2025.2.6)

目录 一、通用大语言模型&#xff1a;DeepSeek-V3 系列 137 二、推理优化模型&#xff1a;DeepSeek-R1 系列 811 三、多模态模型&#xff1a;Janus 系列 10 四、生态整合与部署建议 五、总结与展望 以下为 DeepSeek 在 2024 年 1 月至 2025 年 2 月期间发布的开源模型及其…

第十八章 视图

目录 一、概述 二、语法 2.1. 创建视图 2.2. 查询视图 2.3. 修改视图 2.4. 删除视图 2.5. 示例 三、检查选项 3.1. CASCADED&#xff08;级联&#xff09; 3.2. LOCAL&#xff08;本地&#xff09; 四、视图的更新 五、视图作用 5.1. 简单 5.2. 安全 5.3. 数据独…

数据库课程设计基于Java+MySQL+JDBC+JavaSwing的停车场管理系统源代码+数据库,进出车辆登记,车位管理

&#x1f697;停车场管理系统 运用技术 Java语言MySQL数据库JDBCSwing窗口交互 实现效果 用户登录&#xff1a;输入账号密码&#xff0c;验证通过方可进入&#xff0c;否则给出错误提示&#xff0c;拒绝访问 用户注册&#xff1a;提供用户注册功能&#xff0c;输入用户名&am…

鸿蒙 Next 开发实践:使用 WebView 适配移动端网站

在移动应用开发中&#xff0c;有时我们需要将已有的移动端网站嵌入到原生应用中&#xff0c;以实现快速开发和功能扩展。鸿蒙 Next 提供了强大的 WebView 组件&#xff0c;可以轻松实现这一目标。本文将通过一个简单的示例&#xff0c;展示如何在鸿蒙 Next 应用中使用 WebView …

DeepSeek-R1:开源机器人智能控制系统的革命性突破

目录 引言 一、DeepSeek-R1 的概述 1.1 什么是 DeepSeek-R1&#xff1f; 1.2 DeepSeek-R1 的定位 二、DeepSeek-R1 的核心特性 2.1 实时控制能力 2.2 多传感器融合 2.3 路径规划与导航 2.4 人工智能集成 2.5 开源与模块化设计 2.6 跨平台支持 三、DeepSeek-R1 的技术…