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

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

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

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

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

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

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

jsx 复制代码
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6d95e8570561277e9958e2c7218b64646f701ac4">
  <button type="button" onClick={startImport}>开始导入</button>
</div>
ts 复制代码
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。对旧任务的响应直接返回原状态,可以防止过期事件破坏新流程。

jsx 复制代码
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/51652c9f07b7eaaab956f778f3008867ee1fe5ac">
  <output aria-live="polite">{state.status}</output>
</div>
ts 复制代码
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 派生。事件的处理时机和异步请求依旧由组件或业务服务决定。

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

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

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

jsx 复制代码
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
  <label>选择文件 <input type="file" onChange={selectFile} /></label>
  <button onClick={startImport}>导入文件</button>
</div>
tsx 复制代码
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 缩小类型范围,避免在空闲状态读取不存在的进度属性。

jsx 复制代码
<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 当成业务回滚。

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

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

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

jsx 复制代码
<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

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

jsx 复制代码
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
  <dl><dt>任务状态</dt><dd>{state.status}</dd></dl>
</div>
ts 复制代码
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 适合一个具有内聚性的业务流程,不必把文件读取、列表查询和全局权限都揉进同一状态机。组件卸载时还要取消请求并释放资源。

jsx 复制代码
<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 纯净,将网络操作放到事件或业务服务中,再使用任务身份处理竞态,复杂交互就能具备清晰的数据流与可测试性。

相关推荐
豌豆学姐18 分钟前
图片数字人API接入教程:通过人物图片和音频实现AI口型同步视频生成
java·前端·javascript
qq_2744751529 分钟前
第 14 篇:Class 类详解:ES6 class、静态属性、私有属性、extends 继承、super
前端·ecmascript·es6
木易 士心1 小时前
Web 端反爬与反抓包防御体系全解析
前端·后端·web安全
D_C_tyu1 小时前
AI能力测试·PRD文档分享 | 沉浸式海底世界HTML页面
前端·人工智能·html
只睡四小时1 小时前
LoAF 归因:原生 JS 每次输入 201 次布局读取
开发语言·javascript·性能优化·ecmascript·甘特图·前端性能·loaf
anyup2 小时前
2027 年初,uni-app 官方停更,老项目该何去何从?
前端·vue.js·uni-app
KooFE2 小时前
AI 重塑研发体系,从技能驱动到意图驱动
前端·ai编程
枣把儿2 小时前
剪贴板、截图标注、长截图、自动运镜录屏,我全塞进一个不到 3MB 的免费开源软件里
前端·macos·swiftui
圆心角2 小时前
AI 前端面试:失败重试、知识库、MCP 和大文档,问到多深
前端·面试·ai编程