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

Next.js中TypeScript警告:Property does not exist on type 'any[]'

解决TypeScript警告:Property does not exist on type 'any[]'

问题根源

你把detail的类型声明为any[](数组类型),但从接口http://localhost:3004/products/${productID}的请求来看,返回的是单个产品对象而非数组。当你尝试访问detail.name、detail.image这类对象属性时,TypeScript会报错——因为数组类型本身没有这些属性。

解决方案

1. 定义产品类型接口

先明确产品数据的结构,用TypeScript接口约束类型:

interface Product {
  id: string | number;
  name: string;
  image: string;
  price: number;
  // 可添加其他你需要的属性
}

2. 修正useState的类型与初始值

把detail的类型从any[]改成Product | null,初始值设为null(表示初始状态下没有数据):

const [detail, setDetail] = useState<Product | null>(null);

3. 渲染时处理空值状态

因为初始状态detail是null,直接访问属性会导致运行时错误,所以要先判断数据是否存在:

  • 用条件渲染:{detail && <label>{detail.name}</label>}
  • 或可选链操作符:{detail?.name}

修改后的完整代码

import axios from "axios";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";

// 定义产品类型接口
interface Product {
  id: string | number;
  name: string;
  image: string;
  price: number;
}

export default function Detail() {
  const router = useRouter();
  const productID = router.query.productID;
  // 修正状态类型与初始值
  const [detail, setDetail] = useState<Product | null>(null);

  useEffect(() => {
    // 确保productID存在再发起请求
    if (!productID) return;
    
    const getDetail = async () => {
      const { data: res } = await axios.get(`http://localhost:3004/products/${productID}`);
      setDetail(res);
    };
    getDetail();
  }, [productID]); // 依赖项添加productID,避免路由参数未就绪时请求

  return (
    <div className="pt-5 px-28">
      <label className="text-2xl lg:text-3xl xl:text-3xl font-black">Product Detail - {productID}</label>
      {/* 数据加载完成前显示加载提示 */}
      {detail ? (
        <div className="flex w-full gap-5 mt-3">
          <img src={`../${detail.image}`} className="w-1/2 rounded-2xl aspect-[4/3]" />
          <div>
            <div className="grid">
              <label className="text-xl lg:text-2xl xl:text-2xl ">{detail.name}</label>
              <label className="text-md">IDR {detail.price}</label>
            </div>
            <p className="text-justify italic py-5">
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto sed
              animi unde tempora in. Tempora quos vitae magni modi! Aliquam illum
              sint unde doloribus repellendus nemo facilis eligendi omnis culpa.
            </p>
          </div>
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

额外优化点

  • 在useEffect的依赖项中添加productID,确保路由参数加载完成后再发起请求,避免无效请求。
  • 增加加载状态提示,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:50:21