React useReducer 复杂状态

发布时间:2026/10/2 2:32:11
React useReducer 复杂状态 React useReducer 复杂状态前置React Context 跨层传值目标会写reducer(state, action)理解何时从useState升级。引言一个开关、一个输入框 →useState最爽。状态字段变多、更新规则互相牵扯时一堆setX/setY容易乱。useReducer把「怎么从旧状态算出新状态」收进纯函数reducer(state, action)组件里只dispatch({ type: ... })。本篇 demo计数器 可调步长 重置四种 action。动手完整代码react2/12-usereducer/democdreact2/12-usereducer/demonpminstallnpmrun dev改步长再点step/-step点「重置」回到count0, step1。1. 定义 state / action / reducertype State { count: number; step: number } type Action | { type: inc } | { type: dec } | { type: setStep; step: number } | { type: reset } function reducer(state: State, action: Action): State { switch (action.type) { case inc: return { ...state, count: state.count state.step } case dec: return { ...state, count: state.count - state.step } case setStep: return { ...state, step: action.step } case reset: return { count: 0, step: 1 } default: return state } }约定纯函数同样输入 → 同样输出不写副作用不可变更新返回新对象别直接改state.count ...action.type描述「发生了什么」不是「把 count 设成几」2. 组件里dispatchconst [state, dispatch] useReducer(reducer, { count: 0, step: 1 }) button onClick{() dispatch({ type: inc })}step/button button onClick{() dispatch({ type: dec })}-step/button button onClick{() dispatch({ type: reset })}重置/button input typenumber value{state.step} onChange{(e) dispatch({ type: setStep, step: Number(e.target.value) || 1 }) } /UI 只发意图怎么改状态全在 reducer。3. 何时从 useState 升级继续 useState考虑 useReducer单个布尔 / 字符串下一状态严重依赖上一状态字段少、更新简单同一状态有多种「动作」想把更新逻辑抽到组件外测useReducer Context 常一起做中等复杂度的客户端状态更大更碎的全局状态看 Zustand15 篇。4. 常见坑做法问题reducer 里fetch/ 改 DOM副作用放错地方副作用进 event / effect直接 mutatestateReact 可能检测不到更新action 设计成「setCount(5)」一堆丢失「意图」能工作但难推理简单开关也上 reducer过度useState更短demo 在练什么手写State/Action/reducer用dispatch驱动多动作更新体会「步长影响加减」这种跨字段规则放在 reducer 里更清晰自己改一改加type: double或把初始 state 换成惰性初始化useReducer(reducer, undefined, init)。下一篇React 嵌套路由与布局

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询