React 之 Redux 第二十八节 学习目标与规划大纲及概要讲述

接下来 开始Redux 全面详细的文档输出,主要基于一下几个方面,欢迎大家补充指正

一、Redux 基础概念

为什么需要 Redux

前端状态管理的挑战(组件间通信、状态共享
Redux 解决的问题 :集中式、可预测的状态管理
适用场景 (复杂应用、多组件交互)

Redux 三大核心原则
单一数据源(Single Source of Truth)
状态只读(State is Read-Only,通过 Action 修改)
纯函数修改(Reducers 必须是纯函数)
核心概念
Store :全局状态容器,方法:getState(), dispatch(action), subscribe(listener)
Action :描述状态变化的普通对象(必须包含 type),Action Creator(生成 Action 的函数)
Reducer :纯函数,接收旧状态和 Action,返回新状态,禁止直接修改原状态,返回新对象
Dispatch :触发 Action 的唯一方法

二、Redux 基础使用

创建 Redux Store

javascript 复制代码
import { createStore } from 'redux';
const store = createStore(rootReducer);
定义 Action 和 Reducer

Action 示例:

javascript 复制代码
const increment = () => ({ type: 'INCREMENT' });

Reducer 示例:

javascript 复制代码
const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT': return state + 1;
    default: return state;
  }
};

连接 React 应用

使用 react-redux 库的 Provider 包裹根组件:

javascript 复制代码
import { Provider } from 'react-redux';
<Provider store={store}>
  <App />
</Provider>

组件中获取状态:useSelector Hook

组件中触发 Action:useDispatch Hook

三、Redux 进阶

异步操作处理

中间件(Middleware)的作用

Redux-Thunk:处理异步 Action

javascript 复制代码
const fetchData = () => async (dispatch) => {
  dispatch({ type: 'FETCH_START' });
  const data = await api.getData();
  dispatch({ type: 'FETCH_SUCCESS', payload: data });
};

Redux-Saga (可选):基于 Generator 的复杂异步流管理

组合 Reducer

使用 combineReducers 拆分多个 Reducer:

javascript 复制代码
const rootReducer = combineReducers({
  counter: counterReducer,
  user: userReducer
});

中间件扩展

日志中间件(redux-logger)

开发工具中间件(redux-devtools-extension)

四、Redux 最佳实践与工具

会重点介绍 Redux Toolkit(官方推荐)

createSlice:自动生成 Action & Reducer

configureStore:集成中间件和 DevTools

createAsyncThunk:简化异步逻辑

javascript 复制代码
const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
  },
});

状态持久化

使用 redux-persist 持久化 Store 到本地存储

性能优化

避免不必要的渲染:React.memo + 选择性 useSelector

使用 reselect 缓存复杂计算(Memoized Selectors

五、Redux 生态与替代方案

Redux 生态库

redux-observable(基于 RxJS)

redux-form(表单管理)

现代替代方案

Context API + useReducer(小型应用)

MobX、Recoil、Zustand(其他状态管理方案)

错误之处,麻烦大家评论指正

相关推荐
GISer_Jing15 小时前
明天好好总结汇总分析博客
前端·javascript·面试
做运维的阿瑞18 小时前
Windows 环境下安装 Node.js 和 Vue.js 框架完全指南
前端·javascript·vue.js·windows·node.js
Dontla19 小时前
Tailwind CSS介绍(现代CSS框架,与传统CSS框架Bootstrap对比)Tailwind介绍
前端·css·bootstrap
yinuo20 小时前
uniapp微信小程序安卓手机Touchend事件无法触发
前端
你的人类朋友1 天前
【Node】Node.js 多进程与多线程:Cluster 与 Worker Threads 入门
前端·后端·node.js
闲人编程1 天前
使用Celery处理Python Web应用中的异步任务
开发语言·前端·python·web·异步·celery
excel1 天前
前端读取文件夹并通过 SSH 上传:完整实现方案 ✅
前端
双向331 天前
【征文计划】基于Rokid CXR-M SDK 打造AI 实时会议助手:从连接到自定义界面的完整实践
前端
Lei活在当下1 天前
【业务场景架构实战】6. 从业务痛点到通用能力:Android 优先级分页加载器设计
前端·后端·架构
你的人类朋友1 天前
什么是基础设施中间件
前端·后端