{
  "id": "refactor-a-react-component-safely",
  "type": "prompts",
  "category": "prompts",
  "locale": "zh",
  "url": "/zh/prompts/refactor-a-react-component-safely",
  "title": "安全重构 React 组件的提示词",
  "description": "结构化 AI 代理提示词，用于通过阅读-审计-重构-验证循环安全地重构复杂 React 组件，防止回归问题。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "typescript",
    "nextjs",
    "review"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "使用此提示词进行规范化的组件重构 —— 让代理在修改前进行审计，逐个提取子组件，并在每一步后验证类型，而不是一次性重写整个文件。\n\n## 主要提示词\n\n```txt title=\"Main Prompt\"\nYou are refactoring a React component in a Next.js App Router TypeScript project.\nThe target file is: [INSERT PATH, e.g. src/components/ProductCard.tsx]\n\nRefactor goal: split a large monolithic component into smaller, reusable pieces without\nchanging any observable behavior or UI output.\n\nFollow these phases exactly — do not skip or combine them.\n\nPhase 1 — Audit (no changes):\n  - List every `useState` and `useEffect` call and what it manages.\n  - List every prop the component accepts (with types).\n  - List any inline sub-sections that could be extracted (e.g., a header, a list, a footer).\n  - Identify any duplicated logic (e.g., the same conditional repeated).\n  Output the audit as a numbered list. Stop and wait for my review.\n\nPhase 2 — Extract pure sub-components (one at a time):\n  - For each extractable section identified: create a new file, move the JSX and its\n    required props, export a typed interface for the props, import and use it in the parent.\n  - After each extraction: run `bun run typecheck`. If it fails, fix the error before\n    the next extraction.\n\nPhase 3 — Extract custom hooks:\n  - If any `useEffect` + `useState` pair manages a single concern (e.g., a data fetch,\n    a keyboard listener), extract it to `src/hooks/use<Name>.ts`.\n  - After each extraction: run `bun run typecheck`.\n\nPhase 4 — Remove duplication:\n  - Consolidate any repeated conditional logic into a shared helper.\n  - Do NOT change the logic — only the structure.\n\nPhase 5 — Final verify:\n  - Run `bun run typecheck`.\n  - Show a summary of all files created or edited.\n  - Do NOT change any business logic, API calls, or UI output.\n\nAfter each phase, show the diff and wait for my confirmation before proceeding.\n```\n\n## 实现说明\n\n- 关键约束是行为保持：重构必须是纯粹的结构性更改。要求代理在每个阶段后通过检查差异不包含逻辑更改来确认这一点。\n- TypeScript 是安全网：每次提取后运行 `typecheck` 能立即捕获缺失的 props 或不正确的类型收窄。\n- 自定义 hook 提取仅在该 hook 的状态局限于单个组件实例时才安全。如果状态需要共享，则不要提取 —— 记录并停止。\n\n## 期望的文件变更\n\n```txt\nsrc/components/<name>.tsx            (edited — original component, slimmed down)\nsrc/components/<name>Header.tsx      (new — extracted sub-component)\nsrc/components/<name>List.tsx        (new — extracted sub-component)\nsrc/hooks/use<name>.ts               (new — extracted hook, if applicable)\n```\n\n## 验收标准\n\n- `bun run typecheck` 在每个阶段后退出码为 0。\n- 父组件 props 接口保持不变。\n- 不引入任何 `any` 类型。\n- UI 输出在前后保持像素级一致（通过视觉检查或快照测试验证）。\n\n## 测试命令\n\n```bash\nbun run typecheck\nbun run build\n# if snapshot tests exist:\nbun test --update-snapshots   # run BEFORE refactor to capture baseline\n# then after refactor:\nbun test                       # snapshots should pass without update\n```\n\n## 常见的 AI 错误\n\n- 在将回调提取到子组件时更改其行为（例如，添加带有错误依赖项的 `useCallback`，悄悄改变其触发时机）。\n- 提取持有跨多个组件实例共享状态的 hook，导致状态丢失。\n- 在提取的组件 props 上引入 `any` 类型以规避复杂泛型的解析。\n- 在阶段之间跳过 `typecheck`，导致错误累积且难以追踪。\n\n## 修复提示词\n\n```txt title=\"Fix Prompt\"\nA type error appeared after an extraction or behavior changed. Fix in order:\n1. Run `bun run typecheck` and show me only the errors — do not fix anything yet.\n2. For each error: if it is a missing prop, add it to the extracted component's props interface.\n   If it is an `any` type, resolve it using the type from the parent component's existing interface.\n3. If any logic changed (a conditional, an effect dependency, a callback), revert that specific\n   change only. Show the revert diff before applying it.\n```"
}