generic-react-code-reviewer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Code Reviewer
React代码审查指南
Review React/TypeScript code against production quality standards.
Extends: Generic Code Reviewer - Read base skill for full code review methodology, P0/P1/P2 priority system, and judgment calls.
针对生产级质量标准审查React/TypeScript代码。
扩展自: 通用代码审查工具 - 请阅读基础技能文档以了解完整的代码审查方法论、P0/P1/P2优先级体系以及判断准则。
Pre-Commit Commands
提交前命令
bash
npm run test # Unit tests
npm run type-check # TypeScript strict mode
npm run lint # ESLint/Prettier
npm run build # Production buildbash
npm run test # 单元测试
npm run type-check # TypeScript严格模式检查
npm run lint # ESLint/Prettier代码规范检查
npm run build # 生产环境构建React-Specific Checks
React专项检查
TypeScript Strict Mode
TypeScript严格模式
typescript
// Required tsconfig.json settings
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}- No types for user input or API responses
any - Validate external data with first, then type guard
unknown - Generic types over in reusable utilities
any
typescript
// 必需的tsconfig.json配置
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}- 用户输入或API响应禁止使用类型
any - 先用类型验证外部数据,再使用类型守卫
unknown - 可复用工具中优先使用泛型类型而非
any
Component Patterns
组件模式
| Pattern | Check |
|---|---|
| Props | Interface defined, no |
| State | Typed with Zustand/useState |
| Events | Typed event handlers |
| Refs | |
| 模式 | 检查项 |
|---|---|
| Props | 已定义接口,禁止使用 |
| State | 使用Zustand/useState进行类型定义 |
| Events | 事件处理器已定义类型 |
| Refs | 使用 |
Hook Dependency Arrays
Hook依赖数组
typescript
// P1 Issue: Missing dependencies
useEffect(() => {
fetchData(userId); // userId missing from deps
}, []); // ❌
// Correct
useEffect(() => {
fetchData(userId);
}, [userId]); // ✓Rule: Enable ESLint rule.
react-hooks/exhaustive-depstypescript
// P1级问题:缺失依赖项
useEffect(() => {
fetchData(userId); // userId未在依赖项中
}, []); // ❌
// 正确写法
useEffect(() => {
fetchData(userId);
}, [userId]); // ✓规则: 启用 ESLint规则。
react-hooks/exhaustive-depsState Management (Zustand/Redux)
状态管理(Zustand/Redux)
- Store slices properly typed
- Actions return void (update state directly)
- Selectors memoized for derived state
- Large data (>1MB) in IndexedDB, not localStorage
- Store切片已正确定义类型
- 动作返回void类型(直接更新状态)
- 派生状态的选择器已进行记忆化处理
- 大数据(>1MB)存储在IndexedDB中,而非localStorage
React Query/SWR Patterns
React Query/SWR使用模式
typescript
// Proper typing
const { data } = useQuery<User>({
queryKey: ["user", id],
queryFn: () => fetchUser(id),
});
// Check: staleTime, cacheTime configured
// Check: error boundaries for query failurestypescript
// 正确的类型定义
const { data } = useQuery<User>({
queryKey: ["user", id],
queryFn: () => fetchUser(id),
});
// 检查:已配置staleTime和cacheTime
// 检查:已为查询失败设置错误边界Performance (P1)
性能(P1优先级)
Bundle Size Targets
包大小目标
| Target | Threshold |
|---|---|
| Initial bundle | < 100KB gzipped |
| Lazy-loaded chunks | < 50KB each |
| Total JS | < 300KB |
| 目标 | 阈值 |
|---|---|
| 初始包 | 压缩后 < 100KB |
| 懒加载代码块 | 每个 < 50KB |
| 总JS大小 | < 300KB |
Lazy Loading
懒加载
typescript
// Heavy components (>20KB) MUST be lazy loaded
const HeavyChart = lazy(() => import('./HeavyChart'));
const RichTextEditor = lazy(() => import('./RichTextEditor'));
// Wrap in Suspense
<Suspense fallback={<Skeleton />}>
<HeavyChart />
</Suspense>typescript
// 大型组件(>20KB)必须使用懒加载
const HeavyChart = lazy(() => import('./HeavyChart'));
const RichTextEditor = lazy(() => import('./RichTextEditor'));
// 用Suspense包裹
<Suspense fallback={<Skeleton />}>
<HeavyChart />
</Suspense>Memoization
记忆化处理
typescript
// Expensive calculations
const sortedItems = useMemo(() =>
items.sort((a, b) => a.date - b.date),
[items]
);
// Callback stability for child components
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
// Component memoization (when props are stable)
export const Item = memo(function Item({ data }: Props) {
return <div>{data.name}</div>;
});typescript
// 耗时计算
const sortedItems = useMemo(() =>
items.sort((a, b) => a.date - b.date),
[items]
);
// 子组件稳定回调
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
// 组件记忆化(当props稳定时使用)
export const Item = memo(function Item({ data }: Props) {
return <div>{data.name}</div>;
});Animation (GPU-Accelerated Only)
动画(仅允许GPU加速)
css
/* ✓ DO animate */
transform: translateY(-4px);
opacity: 0.5;
/* ❌ NEVER animate */
width, height, margin, padding, top, leftcss
/* ✓ 推荐动画属性 */
transform: translateY(-4px);
opacity: 0.5;
/* ❌ 禁止动画属性 */
width, height, margin, padding, top, leftAccessibility (P1)
可访问性(P1优先级)
Focus Management
焦点管理
typescript
// Modal focus trapping
useEffect(() => {
if (isOpen) {
const firstFocusable = modalRef.current?.querySelector("button, input");
firstFocusable?.focus();
}
}, [isOpen]);
// Escape to close
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", handleEscape);
return () => window.removeEventListener("keydown", handleEscape);
}, [onClose]);typescript
// 模态框焦点捕获
useEffect(() => {
if (isOpen) {
const firstFocusable = modalRef.current?.querySelector("button, input");
firstFocusable?.focus();
}
}, [isOpen]);
// 按ESC键关闭
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", handleEscape);
return () => window.removeEventListener("keydown", handleEscape);
}, [onClose]);ARIA in JSX
JSX中的ARIA使用
tsx
// Icon-only buttons require labels
<button aria-label="Close modal">
<X className="w-5 h-5" />
</button>
// Dialogs
<div role="dialog" aria-modal="true" aria-labelledby="title">
<h2 id="title">Confirm Action</h2>
</div>tsx
// 仅含图标按钮必须添加标签
<button aria-label="关闭模态框">
<X className="w-5 h-5" />
</button>
// 对话框
<div role="dialog" aria-modal="true" aria-labelledby="title">
<h2 id="title">确认操作</h2>
</div>Quick Review Checklist
快速审查清单
React-Specific (add to base checklist):
- Hook dependencies correct
- Heavy components lazy loaded
- State management typed
- Memoization where beneficial
- Focus management in modals
React专项检查项(添加到基础清单中):
- Hook依赖项配置正确
- 大型组件已启用懒加载
- 状态管理已定义类型
- 已在合适场景使用记忆化处理
- 模态框中已实现焦点管理
See Also
另请参阅
- Generic Code Reviewer - Base review methodology
- Code Review Standards - Full security/performance/accessibility
- Design Patterns - UI consistency
- 通用代码审查工具 - 基础审查方法论
- 代码审查标准 - 完整的安全/性能/可访问性规范
- 设计模式 - UI一致性规范