主题
概念卡片:Redux 状态管理
一句话机制:Redux 用单一 store + 纯函数 reducer + action 描述变化管理全局状态——改状态只能「dispatch 一个带
type的 action」,由 reducer 根据 action 返回全新的 state;react-redux 用connect/useSelector把组件连到 store,中间件(redux-thunk)处理异步 action。
关键代码示例
定义 store / reducer / action:
js
// store/index.js
import { createStore } from 'redux'
const initialState = { counter: 0 }
function reducer(state = initialState, action) {
switch (action.type) {
case 'ADD': return { ...state, counter: state.counter + action.num } // 返回新对象
default: return state
}
}
export const addAction = (num) => ({ type: 'ADD', num }) // actionCreator
export default createStore(reducer)组件连接(演进路径):
js
// 原始:手动 subscribe(繁琐)
componentDidMount() { store.subscribe(() => this.setState({ counter: store.getState().counter })) }
// react-redux:connect / useSelector 自动订阅
import { useSelector, useDispatch } from 'react-redux'
const counter = useSelector(state => state.counter)
const dispatch = useDispatch()
dispatch(addAction(5))三大核心 + 纯函数
| 概念 | 说明 |
|---|---|
| store | 全局唯一的 state 容器 |
| action | 描述「发生了什么」的普通对象,必须有 type |
| reducer | 纯函数 (state, action) => newState |
纯函数:确定输入 → 确定输出,无副作用。reducer 必须纯——不能改原 state、不能发请求、不能写 localStorage。
不变量(必须成立的约束)
- reducer 必须是纯函数:不能直接改原 state,必须返回新对象(
{...state, ...})。 - state 的唯一来源是 store,改 state 只能
dispatch(action)。 - action 是普通对象且必须有
type字段。 - 异步 action 需要中间件(
redux-thunk),直接 dispatch 函数会被拒绝。
踩坑案例
- 现象:reducer 里
state.counter++后返回 state,界面不更新。 原因:原地改、引用没变,Redux 认为没变化。解决:返回{...state, counter: state.counter + 1}。
常见误解
- 直接 dispatch 一个异步函数 → Redux 默认只认普通对象 action,需
redux-thunk。 - 以为每个组件建自己的 store → Redux 是全局单一 store,靠 reducer 拆分管理不同切片。
关联
- 对标 Pinia:概念卡片:Pinia状态管理
- 总览:React技术栈总览
- 源:
B40-资源/语雀-Java开发/前端技术/✅React全家桶/♂️Redux基本使用/(初见/react-redux/中间件/state管理 4 篇)