You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript中API数据传递组件Props类型错误求助

问题分析与解决

错误根源

两个错误的核心都是组件Props类型定义与实际传递/解构不匹配:

  1. HotelCard组件的Props类型被错误设置为hotelInfoProps(这是酒店数据本身的结构),但组件内部却试图解构名为info的属性——而hotelInfoProps里根本没有info这个字段,导致TS报错“Property 'info' does not exist on type 'hotelInfoProps'”。
  2. 父组件HotelPage中,hotelInfo的类型被定义为object | null,既不准确,也和子组件期望的Props类型不兼容,进一步触发了“Type '{ info: object | null; }' is not assignable to type...”的错误。

解决方法(两种可选方案)

方案1:保持通过info属性传递数据(推荐)

这种方式更清晰,组件Props结构明确。

步骤1:修正组件Props类型

在类型定义文件中新增组件专属的Props类型:

// 原hotelInfoProps保持不变
export type hotelInfoProps = {
    name: string;
    description: string;
    location: {
        address: string;
        city: string;
        countryCode: string;
    };
    images: object[];
    review: string;
};

// 新增HotelCard的Props类型
export type HotelCardProps = {
  info: hotelInfoProps | null;
};
步骤2:修改HotelCard组件

更新组件的类型声明,并处理info为null的加载状态:

import { HotelCardProps } from './your-types-path';

export default function HotelCard({ info }: HotelCardProps) {
  // 数据未加载完成时显示占位内容
  if (!info) {
    return <div className='loading'>加载中...</div>;
  }
  
  return (
    <section className='hotel__card'>{info.name}</section>
  )
}
步骤3:修正父组件的状态类型

把hotelInfo的类型从object | null改为hotelInfoProps | null,确保类型兼容:

import { hotelInfoProps } from './your-types-path';

export default function HotelPage() {
  // 修正状态类型
  const [hotelInfo, setHotelInfo] = useState<hotelInfoProps | null>(null);
  const params = useParams();
  const id = params.id;

  async function fetchHotelById() {
    // 增加空值判断,避免无效请求
    if (!id) return;
    const result = await HotelsService.fetchById(id);
    setHotelInfo({
        name: result.name,
        description: result.summary.tagline,
        location: {
            address: result.addressLine,
            city: result.city,
            countryCode: result.countryCode
        },
        images: result.images,
        review: result.reviewInfo.value
    });
  }

  useEffect(() => {
    fetchHotelById();
  }, [id])

  return (
    <>
      <HotelCard info={hotelInfo}/>
    </>
  )
}

方案2:直接传递酒店数据作为组件Props

如果不想用info属性包裹,可以让组件直接接收hotelInfoProps类型的参数:

步骤1:修改HotelCard组件
import { hotelInfoProps } from './your-types-path';

export default function HotelCard(info: hotelInfoProps) {
  return (
    <section className='hotel__card'>{info.name}</section>
  )
}
步骤2:修改父组件的渲染逻辑

通过条件渲染确保只有数据存在时才渲染组件:

import { hotelInfoProps } from './your-types-path';

export default function HotelPage() {
  const [hotelInfo, setHotelInfo] = useState<hotelInfoProps | null>(null);
  // ... 其余代码不变

  return (
    <>
      {/* 数据加载完成后再渲染组件 */}
      {hotelInfo && <HotelCard {...hotelInfo}/>}
    </>
  )
}

内容的提问来源于stack exchange,提问作者Lilly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:47:10