【发布时间】: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<CartItemType>(没有[]),因为您要求的是单个项目,不是吗? -
您似乎在告诉编译器
data是一个数组CartItemType[]。您似乎希望它只是一个对象 (CartItemType)。 -
@moonwave99 天哪!非常感谢你们所有人。我有一种感觉,我只是错过了一些愚蠢的东西 :) 这很有效。而且我还刚刚在退货中添加了“{data?.name}”,这样我就不会再收到“未定义”错误了:)
标签: javascript json reactjs typescript object