next.js Typescript中的类型“any[ ]”上不存在属性

bf1o4zei  于 2023-01-17  发布在  TypeScript
关注(0)|答案(1)|浏览(716)

我在Next Js中使用了Textscript。我的项目运行良好,但我的脚本中出现了一些警告,如“Property does not existed on type any[]”,在name、image和price属性下面有红线。我知道有很多类似的问题,但我还是不明白

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

export default function Detail() {
  const router = useRouter();
  const productID = router.query.productID;
  const [detail, setDetail] = useState<any[]>([]);

  useEffect(() => {
    const getDetail = async () => {
      const { data: res } = await axios
      .get("http://localhost:3004/products/" + productID );
      setDetail(res);
    };
    getDetail();
  }, []);

  return (
    <div className="pt-5 px-28">
      <label className="text-2xl lg:text-3xl xl:text-3xl font-black">Product Detail - {productID}</label>
      <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>
    </div>
  );
}
py49o6xq

py49o6xq1#

const [detail, setDetail] = useState<any[]>([]);

此代码将变量detail的类型设置为any[]any[]any的数组。
数组没有pricename这样的属性,所以这就是导致错误的原因,取而代之的是,你可以将detail的类型设置为{ price: string, name: string, image: string },并用空字符串初始化这个变量。

const [detail, setDetail] =
  useState <
  {
    price: string,
    name: string,
    image: string,
  } >
  {
    price: "",
    name: "",
    image: "",
  };

看起来你对细节的类型有点困惑。a是一个元素还是一个元素数组?

相关问题