React Router v6中history.push报错Uncaught TypeError的解决求助
问题原因与解决方案
核心问题
你使用的react-router-dom@6.x已经彻底移除了通过组件props传递history、location、match的机制,所以从props里解构出来的history是undefined,调用history.push自然会抛出Cannot read properties of undefined (reading 'push')错误。
另外你尝试的this.context和this.prop完全不适用——你的ProductScreen是函数组件,根本不存在this对象,这两种写法本身就不符合函数组件的语法规范。
正确解决步骤
1. 导入useNavigate钩子
在ProductScreen.js文件顶部添加导入语句:
import { useNavigate } from 'react-router-dom';
2. 初始化导航函数
在组件内部调用useNavigate获取导航方法:
const ProductScreen = () => { const navigate = useNavigate(); // 其他组件逻辑代码... };
3. 替换history.push为navigate
修改addToCartHandler函数的导航逻辑:
const addToCartHandler = () => { navigate(`/cart/${id}?qty=${qty}`); };
额外说明
如果是类组件需要实现导航,react-router-dom@6.x提供了withRouter高阶组件,但函数组件优先使用useNavigate钩子即可,这是v6版本推荐的标准用法。
内容的提问来源于stack exchange,提问作者Nirav Parekh
相关产品推荐
相关产品推荐

