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

react-router-dom导入报错:'withRouter' is not exported 问题求解

错误原因

你安装的react-router-dom为v6及以上版本,该版本已经正式移除了withRouter高阶组件,因此触发导入失败报错。

解决方案

方案1:降级到v5版本(无需修改现有代码)

执行以下命令安装v5版本的依赖:

npm install react-router-dom@5.x react-router@5.x

安装完成后重启项目即可。

方案2:适配v6版本(推荐)

由于你当前的MenuItem本身就是函数组件,可直接使用v6提供的路由Hook替代withRouter:

  1. 用useNavigate替代原history对象的能力,原history.push(path)对应改为navigate(path),history.replace(path)对应改为navigate(path, {replace: true})
  2. 修改后的代码示例如下:
import React from 'react';
import { useNavigate } from 'react-router-dom';

import './menu-item.scss';

const MenuItem = ({ title, imageUrl, size }) => {
  const navigate = useNavigate();
  // 如果需要获取路由参数、当前路径,可额外引入useParams、useLocation Hook
  return (
    <div className={`${size} menu-item`}>
      <div
        className='background-image'
        style={{
          backgroundImage: `url(${imageUrl})`,
        }}
      />
      <div className='content'>
        <h1 className='title'>{title.toUpperCase()}</h1>
        <span className='subtitle'>SHOP NOW</span>
      </div>
    </div>
  );
};

export default MenuItem;

如果项目中存在必须使用withRouter的类组件场景,可手动封装自定义withRouter高阶组件:

// src/utils/withRouter.js
import { useLocation, useNavigate, useParams } from "react-router-dom";

export function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }
  return ComponentWithRouterProp;
}

在需要使用的文件中引入上述自定义withRouter,原有代码逻辑无需改动即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:24:05