React项目ProductScreen通过id跳转后无法读取undefined属性渲染数据
问题修复方案
错误原因
- App.js中ProductScreen组件的
productsprops写在了组件闭合标签</ProductScreen>外面,导致该参数根本没有传递到组件内部,ProductScreen拿到的products是undefined,触发"cannot read property of undefined"报错 - ProductScreen没有获取路由参数中的商品id,也没有从全部商品数组中筛选出对应id的单个商品,直接把整个products数组当成单个商品使用,数据结构不匹配
- ProductScreen的img标签alt属性使用了未声明的
product变量,同时描述字段拼写错误(descrption应为description),描述字段前多写了$符号
修复代码
1. 修复App.js路由部分代码
把原来的ProductScreen对应路由替换为以下内容:
<Route exact path="/product/:id" > <ProductScreen products={products} cartItems={cartItems} onAdd={ onAdd }/> </Route>
2. 替换ProductScreen.js全部代码
import './ProductScreen.css'; import { useParams } from 'react-router-dom' const ProductScreen = ({ products }) => { // 从路由中获取商品id const { id } = useParams() // 匹配对应id的单个商品 const product = products.find(item => String(item.id) === id) // 容错处理:未找到对应商品时显示提示 if(!product) return <div>当前商品不存在</div> return ( <div className="productscreen"> <div className="productscreen__left"> <div className="left__image"> <img className="small" src={product.image} alt={product.name} /> </div> <div className="left__info"> <p className="left__name">{product.name}</p> <p>${product.price}</p> <p>{product.description}</p> </div> </div> </div> ) } export default ProductScreen
内容的提问来源于stack exchange,提问作者Yusuf
相关产品推荐
相关产品推荐

