React单商品页报Cannot read properties of undefined (reading 'params')如何解决
问题根因
你当前使用的是react-router-dom v6版本,该版本已经移除了自动注入到路由组件props中的match、history、location对象,因此ProductScreen组件中接收的match参数为undefined,访问match.params就会抛出你遇到的类型错误。
修复方案
直接使用v6提供的useParams钩子获取路由参数即可,修改ProductScreen组件代码如下:
import React, { useState, useEffect } from 'react' import { Link, useParams } from 'react-router-dom' // 新增引入useParams import { Row, Col, Image, ListGroup, Card, Button } from 'react-bootstrap' import Rating from '../components/Rating' import axios from 'axios' const ProductScreen = () => { // 移除原有match参数 const [product, setProduct] = useState({}) const { id } = useParams() // 调用钩子获取路由中的id参数 useEffect(() => { const fetchProduct = async () => { const { data } = await axios.get(`/api/products/${id}`) // 直接使用获取到的id setProduct(data) } fetchProduct() }, [id]) // 依赖项改为id // 后续组件渲染逻辑保持不变即可
补充优化建议
可以为商品数据增加加载状态判断,或者在渲染商品属性时使用可选链语法product?.xxx,避免接口返回前访问空对象属性抛出额外错误。
内容的提问来源于stack exchange,提问作者Lethal-Bacon
相关产品推荐
相关产品推荐

