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

如何在useEffect中使用useParams?出现参数读取未定义错误

解决useEffect中使用useParams时的"Cannot read properties of undefined (reading 'params')"错误

问题根因

你已经通过useParams()解构出了id,但在useEffect里错误使用了match.params.id——在React Router v6版本中,match对象已经被移除,不存在这个变量,所以match是undefined,访问它的params属性就会抛出这个错误。

修复后的代码

直接使用useParams()解构出来的id,同时更新useEffect的依赖项:

const dispatch = useDispatch();
const { id } = useParams();

useEffect(() => {
  dispatch(getProductDetails(id));
}, [dispatch, id]);

补充说明

React Router v6中,路由参数直接通过useParams()获取,替代了v5版本里match.params的用法。你的路由配置是正确的,组件通过element属性挂载,useParams()可以正常拿到路由参数,只需要替换掉代码里的match.params.id部分即可。

内容的提问来源于stack exchange,提问作者shoaib ulla khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:20:22