You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React报错Cannot read properties of undefined ('reading params')求助

报错原因

Cannot read properties of undefined ('reading params') 报错的直接原因是代码中的match对象为undefined,无法读取其下的params属性。该问题绝大多数场景是你的项目使用了React Router v6版本,该版本废弃了原有路由组件props自动注入的match、history、location属性,需要改用官方提供的Hook获取路由参数和导航能力。

修复方案

  • 从react-router-dom中导入useParams Hook,若仍需要原来history的导航能力,同步导入useNavigate
  • 在组件内调用useParams获取路由参数id,替换原有的match.params.id写法
  • 如果用到history的导航功能,用useNavigate返回的方法替代原有history的相关API调用

修改后的代码示例:

import { useParams, useNavigate } from 'react-router-dom' // 新增路由相关Hook导入

const ProductScreen = () => { // 移除props中未生效的match、history
    const [qty, setQty] = useState(1);
    const dispatch = useDispatch();
    const { id } = useParams() // 直接调用Hook获取路由id参数
    const navigate = useNavigate() // 替代原有history的导航能力,跳转用法为navigate('/目标路径')
    
    const productDetails = useSelector((state) => state.getProductDetails);
    const { loading, error, product } = productDetails;

    useEffect(() => {
        if (product && id !== product._id){
            dispatch(getProductDetails(id));
        }
    }, [dispatch, product, id]); // 依赖项替换为id

如果你使用的是React Router v5及以下版本仍出现该问题,检查对应路由组件是否使用了withRouter高阶组件包裹,未包裹的组件无法自动注入match等路由属性。


内容的提问来源于stack exchange,提问作者Cuttuhryn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:36:03