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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:57:01