【问题标题】:ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading \'name\')
【发布时间】:2022-09-26 16:50:00
【问题描述】:

我收到以下错误 -

ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading \'name\')

import React from \'react\';
import {useParams } from \'react-router-dom\';
import products from \'../products\';

const ProductDetail = () => {

    const { id } = useParams();

    const product = products.find((p) => p._id === Number(id));

    return (
        <div>
            {product.name}
        </div>
    );
}

export default ProductDetail;

产品.js

const products = [
  {
    \'_id\': \'1\',
    \'name\': \'Samsubg A001\',
    \'description\':
      \'testinggggg\',
    \'brand\': \'Samsung\',
    \'category\': \'Mobile\',
    \'price\': 10,
    \'Stock\': 20,
    \'rating\': 4.5,
    \'Reviews\': 12,
  },
  • 如果使用find 找不到结果,则返回undefined。您似乎没有具有匹配 ID 的产品。如果没有更多上下文,我们无法提供真正的答案,只能说 - 使用条件渲染或类似模式计划找不到匹配项。
  • 您已经尝试过哪些调试步骤?一个只有错误消息和代码块的问题几乎不可能有任何质量。我们希望在提出问题之前您自己进行研究,如果您仍然遇到困难,请提供有关您的尝试的详细信息以及您在搜索中发现的内容。
  • @BrianThompson 通过将严格相等运算符(===)替换为相等运算符(==)解决了错误

标签: reactjs


【解决方案1】:

你确定product 变量不是未定义的吗?似乎您正在尝试访问未定义变量中的 name 属性。

【讨论】:

    【解决方案2】:

    您可以通过检查产品是否未定义来短路,或者您可以使用像 product?.name 这样的可选链接

    【讨论】:

      【解决方案3】:

      const product = products.find((p) => p._id === String(id));

      那可行

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-09
        • 2022-07-21
        • 2022-07-22
        • 2022-10-13
        相关资源
        最近更新 更多