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

React Router DOM报错:withRouter导出未找到,寻求技术帮助

解决React Router DOM中withRouter找不到的问题

这个错误是因为React Router DOM v6 已移除withRouter高阶组件,它不再作为官方导出内容存在,所以你导入时会提示找不到该导出。

解决方案

根据你的组件类型选择对应处理方式:

1. 函数组件(推荐)

直接使用React Router v6提供的hooks替代withRouter,常用的hooks包括:

  • useLocation:获取当前路由位置信息
  • useNavigate:实现路由跳转
  • useParams:获取URL参数
  • useMatch:匹配路由规则

示例代码:

import { useLocation, useNavigate, useParams } from 'react-router-dom';

function MyComponent() {
  const location = useLocation();
  const navigate = useNavigate();
  const params = useParams();

  // 使用这些路由相关数据
  return <div>当前路径:{location.pathname}</div>;
}

2. 类组件

如果仍在使用类组件,需要自己封装一个withRouter高阶组件,通过hooks获取路由属性后传递给类组件:

import { useLocation, useNavigate, useParams, useMatch } from 'react-router-dom';
import React from 'react';

const withRouter = (Component) => {
  const Wrapper = (props) => {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    const match = useMatch(location.pathname);

    return (
      <Component
        {...props}
        location={location}
        navigate={navigate}
        params={params}
        match={match}
      />
    );
  };

  return Wrapper;
};

// 使用方式
class MyClassComponent extends React.Component {
  render() {
    const { location, navigate, params } = this.props;
    return <div>当前路径:{location.pathname}</div>;
  }
}

export default withRouter(MyClassComponent);

额外提示

如果你的项目是从React Router v5升级到v6的,除了withRouter,还有其他API变化(比如Switch替换为Routes,component/render属性替换为element等),建议同步检查其他路由相关代码是否符合v6规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:16:15