You need to enable JavaScript to run this app. 使用TypeScript最佳实践改造React组件的实现方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 23:57:03