TypeError: 无法读取未定义的属性(读取 ‘name’),问题在哪里?

huangapple go评论78阅读模式
英文:

TypeError: Cannot read properties of undefined (reading 'name'), where is the problem?

问题

以下是您要翻译的内容:

Name, distribution and price are all fine only when I give category I get this error. I am giving it the way it is structured in the database and still getting the error. Problem with words? Someone will point out a little mistake kindly.

import React, { useEffect, useState } from "react";
import Layout from "../Components/Layout/Layout";
import axios from "axios";
import { useParams } from "react-router-dom";

const ProductDetails = () => {
  const params = useParams()
  const [product, setProduct] = useState({});

  // initall details
  useEffect(() => {
    if (params?.slug) getProduct();
  }, [params?.slug]);
  // getProduct
  const getProduct = async () => {
    try {
      const { data } = await axios.get(
        `/api/v1/product/get-product/${params.slug}`
      );
      setProduct(data?.product);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <Layout>
      <div className="row grid lg:grid-cols-3 m-4">
        <div className="col-1">
          <img
            className="w-96 h-96"
            src={`/api/v1/product/product-photo/${product._id}`}
            alt={product.name}
          />
        </div>
        <div className="col-2">
          <h1 className="text-center">Products Details</h1>
          <h4>Name: {product.name} </h4>
          <h4>Description: {product.description} </h4>
          <h4>Price: {product.price}</h4>
          <h4>Category: {product.category.name}</h4>
        </div>

        <div className="col-3">
          <p>Similar Products</p>
        </div>
      </div>
    </Layout>
  );
};

export default ProductDetails;

TypeError: 无法读取未定义的属性(读取 ‘name’),问题在哪里?


<details>
<summary>英文:</summary>
Name,distribution and price are all fine only when I give category I get this error. I am giving it the way it is structured in the database and still getting the error. Problem with words? Someone will point out a little mistake kindly.

import React, { useEffect, useState } from "react";
import Layout from "../Components/Layout/Layout";
import axios from "axios";
import { useParams } from "react-router-dom";

const ProductDetails = () => {
const params = useParams()
const [product, setProduct] = useState({});

// initall details
useEffect(() => {
if (params?.slug) getProduct();
}, [params?.slug]);
// getProduct
const getProduct = async () => {
try {
const { data } = await axios.get(
/api/v1/product/get-product/${params.slug}
);
setProduct(data?.product);
} catch (error) {
console.log(error);
}
};
return (
<Layout>
<div className="row grid lg:grid-cols-3 m-4">
<div className="col-1 ">
<img
className="w-96 h-96"
src={/api/v1/product/product-photo/${product._id}}
alt={product.name}
/>
</div>
<div className="col-2">
<h1 className="text-center">Products Details</h1>
<h4>Name: {product.name} </h4>
<h4>Description: {product.description} </h4>
<h4>Price: {product.price}</h4>
<h4>Cetegory: {product.category.name}</h4>
</div>

    &lt;div className=&quot;col-3&quot;&gt;
&lt;p&gt;Similar Products&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/Layout&gt;

);
};

export default ProductDetails;


[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/RigBc.png
</details>
# 答案1
**得分**: 1
<h4>类别: {product?.category?.name}</h4>
这里我使用了“&&”(与)运算符的简写形式。首先,我们会检查“product”是否可用,如果是,则会访问“category”变量,然后我们会检查“category”对象是否存在“name”键。这将修复您的错误。
<details>
<summary>英文:</summary>
&lt;h4&gt;Category: {product?.category?.name}&lt;/h4&gt;
Here I&#39;ve used the shorthand for the &amp;&amp; (and) operator. First, we&#39;ll check if the &quot;product&quot; is available, if yes then we&#39;ll access the &quot;category&quot; variable and after that, we&#39;ll check if &quot;name&quot; key exists for the &quot;category&quot; object. So this will fix your error.
</details>
# 答案2
**得分**: 0
<h4>类别:{product.category && product.category.name}</h4>
这将在尝试访问其名称属性之前检查product.category是否存在。
请确保验证API响应的结构,并确保类别属性正确地填充了必要的数据,包括名称。
<details>
<summary>英文:</summary>
&lt;h4&gt;Category: {product.category &amp;&amp; product.category.name}&lt;/h4&gt;
This will check if product.category exists before trying to access its name property.
Make sure to verify the structure of the API response and ensure that the category property is properly populated with the necessary data also with name.
</details>
# 答案3
**得分**: -1
我建议您使用产品的所有代码。此外,您需要检查产品类别名称上的异常情况。
<details>
<summary>英文:</summary>
I recommend you to use product? all of the code. Also, You need to check exception on product.category.name 
</details>

huangapple
  • 本文由 发表于 2023年6月15日 17:37:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定