使用TypeScript最佳实践改造React组件的实现方法咨询
React组件TypeScript重构方案
完整重构后代码
import axios from "axios"; import { useEffect, useState } from "react"; // 定义列表项数据结构 interface ListItem { text: string; } // 定义组件Props类型 interface ComponentProps { isLists: boolean; show: boolean; lists: ListItem[]; } // 定义接口返回值类型,可根据实际业务调整 type TradResponse = string; const Component = (props: ComponentProps) => { const { isLists: listeOuNon, show: montreComposant, lists: listes } = props; // 状态移到组件顶层,避免违反Hooks调用规则 const [trad, ajoutTrad] = useState<TradResponse>(""); useEffect(() => { // 仅当需要展示列表时发起请求 if (!listeOuNon) return; (async () => { // 给axios请求添加泛型约束响应类型 const reponse = await axios.get<TradResponse>("/api/trad"); if (reponse.status === 200) { ajoutTrad(reponse.data); } })(); // 补充依赖数组,避免无限触发请求 }, [listeOuNon]); if (montreComposant) { return ( <div> {listeOuNon ? ( <div> <div>le super titre {trad}</div> <div> <ul> {listes.map((elements, index) => ( <li key={index}>{elements.text}</li> ))} </ul> </div> </div> ) : ( <div> <div>le super titre</div> <div>Bonjour tout le monde</div> </div> )} </div> ); } else { return <></>; } }; export default Component;
核心优化说明
- 类型定义:使用
interface严格定义组件入参、数据结构、接口返回值的类型,彻底替换any类型,获得编译阶段的类型校验和开发阶段的智能提示 - 语法修复:修正原有代码中错误的组件导出写法、缺失的变量名定义问题,将Hooks移到组件顶层,符合React Hooks调用规则
- 逻辑优化:给
useEffect补充依赖数组,避免接口重复请求,仅在需要展示列表时发起接口调用 - 类型安全:给
useState、axios请求添加泛型约束,明确所有变量的类型边界 - 代码规范:使用解构赋值简化props取值,统一变量命名规范,删除冗余注释
内容的提问来源于stack exchange,提问作者Luc Mosser
相关产品推荐
相关产品推荐

