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中导入useParamsHook,若仍需要原来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
相关产品推荐
相关产品推荐

