【发布时间】: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