React useReducer 实战:复杂组件状态转换与可测试的业务流程

简介: 本文介绍如何用 `useReducer` 管理上传/导入面板的复杂状态。通过 TypeScript 判别联合定义唯一状态(idle/running/success/error),事件驱动纯函数更新,避免多 `useState` 冲突;结合任务 ID 防竞态、进度校验、取消重试与边界测试,提升可维护性与可测试性。(239字)

当一个上传面板同时维护文件、进度、错误、取消和重试时,多个 useState 很容易产生互相矛盾的值。useReducer 可以把状态转换集中为纯函数,使事件与界面状态之间的关系更清楚。本文以导入任务为例,采用 TypeScript 判别联合描述业务状态。

1. 确定状态而不是布尔变量数量

不要分别维护 isLoading、isSuccess 和 isError 等可能同时为真的变量。导入任务可以处于 idle、running、success 或 error 中的一个状态。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/71a691dfd4be014c98dfd53761b08a06dc9174e9">
  <section aria-label="导入任务">
    <h2>批量导入</h2>
    <p>选择数据文件后开始处理</p>
  </section>
</div>
type State =
  | {
    status: 'idle' }
  | {
    status: 'running'; id: string; progress: number }
  | {
    status: 'success'; count: number }
  | {
    status: 'error'; message: string };

2. 为状态转换建立事件协议

事件应表达发生了什么,而非直接描述需要设置哪几个字段。异步进度事件携带任务 ID,使 reducer 能判断它是否仍属于当前操作。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6d95e8570561277e9958e2c7218b64646f701ac4">
  <button type="button" onClick={startImport}>开始导入</button>
</div>
type Action =
  | {
    type: 'start'; id: string }
  | {
    type: 'progress'; id: string; value: number }
  | {
    type: 'success'; id: string; count: number }
  | {
    type: 'error'; id: string; message: string }
  | {
    type: 'reset' };

3. 编写纯 reducer

reducer 不发送请求、不生成随机值,也不操作 DOM。对旧任务的响应直接返回原状态,可以防止过期事件破坏新流程。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/51652c9f07b7eaaab956f778f3008867ee1fe5ac">
  <output aria-live="polite">{state.status}</output>
</div>
function reducer(state: State, action: Action): State {
   
  if (action.type === 'reset') return {
    status: 'idle' };
  if (action.type === 'start') return {
    status: 'running', id: action.id, progress: 0 };
  if (state.status !== 'running' || state.id !== action.id) return state;
  switch (action.type) {
   
    case 'progress': return {
    ...state, progress: Math.max(state.progress, Math.min(100, action.value)) };
    case 'success': return {
    status: 'success', count: action.count };
    case 'error': return {
    status: 'error', message: action.message };
  }
}

4. 把状态接入组件

使用 useReducer 初始化状态,视图从 state.status 派生。事件的处理时机和异步请求依旧由组件或业务服务决定。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/5de111f3a6f0157e24507ff84a74e361871d8be2">
  <button disabled={state.status === 'running'} onClick={startImport}>
    {state.status === 'running' ? '处理中' : '开始'}
  </button>
</div>
const [state, dispatch] = useReducer(reducer, { status: 'idle' } satisfies State);

5. 在事件处理器中启动异步操作

请求发生于用户明确点击开始时,通常不必依赖 effect 监听状态再启动。业务服务接收进度回调和取消信号。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
  <label>选择文件 <input type="file" onChange={selectFile} /></label>
  <button onClick={startImport}>导入文件</button>
</div>
async function runImport(file: File, signal: AbortSignal) {
  const id = crypto.randomUUID();
  dispatch({ type: 'start', id });
  try {
    const count = await importFile(file, { signal, onProgress: value => dispatch({ type: 'progress', id, value }) });
    dispatch({ type: 'success', id, count });
  } catch (error) {
    if (!signal.aborted) dispatch({ type: 'error', id, message: '导入失败' });
  }
}

6. 让进度只在运行状态可见

判别联合能够帮助 TypeScript 缩小类型范围,避免在空闲状态读取不存在的进度属性。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff3614ed36c1ebaeabd92a47ed560eed4799e07a">
  {state.status === 'running' && (
    <progress value={state.progress} max={100} aria-label="导入进度" />
  )}
</div>

进度的单位要与服务端或本地任务统一。网络上传完成不一定表示服务端已经解析并写入数据。

7. 取消任务并区分本地与远程状态

取消读取后可重置本地视图,但远程任务如果已经开始,可能需要独立取消接口。不要将 abort 当成业务回滚。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/690f209d77c4b377f85c70fd81fbe6842ab0b57f">
  {state.status === 'running' && <button onClick={cancelImport}>取消</button>}
</div>
function cancelImport() {
  controllerRef.current?.abort();
  dispatch({ type: 'reset' });
}

8. 错误重试应创建新任务身份

失败状态保留错误信息;重试使用上次选择的文件并生成新的任务标识。是否可以重复提交由接口幂等契约决定。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
  {state.status === 'error' && (
    <section role="alert"><p>{state.message}</p><button onClick={retry}>重试</button></section>
  )}
</div>

重试不能复用可能已经过期的 AbortSignal。对于写入请求,服务端应有独立的任务身份或幂等键。

9. 独立测试 reducer

纯函数适合做表驱动测试。重点验证非法转换、不同任务的响应和边界进度,而不仅是正常成功流程。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
  <dl><dt>任务状态</dt><dd>{state.status}</dd></dl>
</div>
const running: State = {
    status: 'running', id: 'current', progress: 40 };
expect(reducer(running, {
    type: 'success', id: 'old', count: 10 })).toBe(running);
expect(reducer(running, {
    type: 'progress', id: 'current', value: 80 })).toEqual({
    ...running, progress: 80 });

10. 明确组件与服务的边界

一个 reducer 适合一个具有内聚性的业务流程,不必把文件读取、列表查询和全局权限都揉进同一状态机。组件卸载时还要取消请求并释放资源。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
  {state.status === 'success' && <p role="status">已导入 {state.count} 条记录</p>}
</div>

测试界面时验证状态变化、错误信息和取消后的重新开始。React 开发模式可能额外调用纯 reducer 来帮助发现副作用,所以不要在 reducer 里执行一次性动作。

总结

useReducer 的核心价值是显式表达状态转换规则。保持 reducer 纯净,将网络操作放到事件或业务服务中,再使用任务身份处理竞态,复杂交互就能具备清晰的数据流与可测试性。

相关文章
|
9天前
|
域名解析 人工智能 Linux
|
19天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17571 63
|
17天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
3天前
|
人工智能 安全 网络安全
|
7天前
|
云安全 数据采集 人工智能
|
8天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1385 5
|
14天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2444 8
|
19天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
3956 22
|
21天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是DeepSeek AI开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、跑命令、处理表格、联网搜索等操作。免费开源,兼容Windows/macOS/Linux,提供桌面端与网页端,可灵活安装插件扩展能力。

热门文章

最新文章