【问题标题】:"Property 'name' does not exist on type" typescript problem in react website反应网站中的“类型上不存在属性'名称'”打字稿问题
【发布时间】:2021-07-25 09:55:51
【问题描述】:

我正在尝试在 React with Typescript 中创建一个简单的电子商务网站(我的第一个 React 和 Typescript 网站)。我有一个产品列表,当我按下产品时,我会转到产品页面。我在尝试在页面上显示有关产品的信息时遇到了问题。

我正在从我的 RESTful API 获取数据,我可以控制台记录正确的产品及其所有信息 - 但我无法在页面上返回名称、价格、图像等。尝试使用 data.name 时出现两个错误“对象可能是'未定义'”和“属性'名称'不存在于类型'CartItemType []”。

有人可以帮忙吗?我尝试了很多不同的方法,但我无法让它显示信息 - 只有通过 match.params.productId 的 productid。

import React, { useState, useEffect } from "react";
import { BrowserRouter, Link, match, NavLink, Route, Switch, useParams } from 'react-router-dom';
import { useQuery } from "react-query";

export type CartItemType = {
    productId: number;
    category: string;
    description: string;
    img_path: string;
    price: number;
    name: string;
    quantity: number;
  };

const ProductDetails = ({match}: {match: any}) => {
      const getProduct = async (): Promise<CartItemType[]> =>
      await (await fetch('http://localhost:3000/products/'+ match.params.productId)).json(); 
      const {data} = useQuery<CartItemType[]>(
        'product',
        getProduct
      );

      if(data){
        console.log(data) //gives me the correct product based on URL. For example: 
{productId: 12, name: "Green tea", price: 40, img_path: "Images/Teas/12.png", description: "Tasting notes: Cool mint}
        
console.log(data.name) //gives the error "Property 'name' does not exist on type 'CartItemType[]
      }

return (
  <div>
 <p>Product name: {data.name}</p> // gives error "Object is possibly 'undefined' and "Property 'name' does not exist on type 'CartItemType[]
</div>
)
}

export default ProductDetails



【问题讨论】:

  • 应该是useQuery&lt;CartItemType&gt;(没有[]),因为您要求的是单个项目,不是吗?
  • 您似乎在告诉编译器 data 是一个数组 CartItemType[]。您似乎希望它只是一个对象 (CartItemType)。
  • @moonwave99 天哪!非常感谢你们所有人。我有一种感觉,我只是错过了一些愚蠢的东西 :) 这很有效。而且我还刚刚在退货中添加了“{data?.name}”,这样我就不会再收到“未定义”错误了:)

标签: javascript json reactjs typescript object


【解决方案1】:

您正在从 'http://localhost:3000/products/'+ match.params.productId 获取一个特定项目,它返回一个特定对象,例如: {productId: 12, name: "Green tea", price: 40, img_path: "Images/Teas/12.png", description: "Tasting notes: Cool mint}

但是你告诉 typescript 它会在这里返回一个数组:CartItemType[]

因此,当您执行 console.log(data.name) 时,typescript 会推断它为 [].name 并抱怨数组没有 name 属性。

CartItemType[] 的用法更新为仅CartItemType

【讨论】:

  • 谢谢!我有一种感觉,我只是错过了一些小事。我还最终在退货中使用了“{data?.name}”,这样我就不会再收到“未定义”错误了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2020-12-18
  • 2018-03-27
  • 2020-11-10
  • 1970-01-01
  • 2019-05-05
  • 2017-03-02
相关资源
最近更新 更多