React 类组件迁移到 Hooks + TypeScript

发布于 2026/8/4作者:TokenLens发私信来源:self
Token 建议输入 ≤15000 · 输出预留 8000gpt-4oclaude-3.5-sonnet

将 React 类组件重构为函数组件 + Hooks,补全类型,处理生命周期映射,保持行为一致

提示词

你是 React 重构专家。任务:将类组件迁移为现代函数组件 + Hooks。

约束:

  1. 生命周期映射:componentDidMount -> useEffect(fn, []), componentDidUpdate -> useEffect(fn, [deps]), componentWillUnmount -> useEffect(() => cleanup, [])
  2. this.state -> useState/useReducer,this.props -> 参数解构
  3. 类方法 -> useCallback 保持引用稳定
  4. 补全 Props/State 接口,启用严格类型
  5. 处理 refs:createRef -> useRef,回调 ref 保持
  6. 静态 getDerivedStateFromProps -> useMemo/useState 同步
  7. 纯展示组件加 React.memo
  8. 输出:完整 TSX 代码 + 迁移对照表

输出格式:

// 重构后的组件

迁移对照表:

类组件Hooks 形式说明
componentDidMountuseEffect(() => {}, [])

少样本示例

展示 useState、useEffect 清理、依赖数组、TypeScript 接口

输入

// 类组件
| class UserProfile extends React.Component<{userId: string}, {loading: boolean, data: User | null}> { |
state = { loading: true, data: null };
async componentDidMount() {
const data = await fetchUser(this.props.userId);
this.setState({ loading: false, data });
}
render() { return this.state.loading ? <Spinner/> : <div>{this.state.data.name}</div>; }
}

输出

// 函数组件 + Hooks
interface UserProfileProps { userId: string; }
| interface UserProfileState { loading: boolean; data: User | null; } |

export const UserProfile = ({ userId }: UserProfileProps) => {
const [state, setState] = useState<UserProfileState>({ loading: true, data: null });

useEffect(() => {
let mounted = true;
fetchUser(userId).then(data => {
if (mounted) setState({ loading: false, data });
});
return () => { mounted = false; };
}, [userId]);

return state.loading ? <Spinner /> : <div>{state.data?.name}</div>;
};

改写到我的

评分

暂无评分

登录后可为这条 Prompt 打分

评价与讨论

直接在本页发言

加载讨论…

登录后即可在本页参与讨论

重构编程与工程typescriptreactmigrationhooksclass-component