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

react-router v6中withRouter导入报错及替代方案咨询

报错原因

React Router v6 版本官方已完全移除 withRouter 高阶组件,因此直接从 react-router-dom 导入会触发导入失败报错,这是版本迭代的正常破坏性变更,并非代码拼写错误导致。

替代实现方案

分两种场景适配:

场景1:项目使用函数组件

优先直接使用 React Router v6 提供的原生 Hooks 替代 withRouter 功能,无需引入额外高阶组件:

  • 替代原 history 跳转能力:使用 useNavigate() Hook
  • 替代原 match.params 获取路由参数:使用 useParams() Hook
  • 替代原 location 获取当前路由信息:使用 useLocation() Hook

示例代码:

// 导入所需Hook
import { useNavigate, useParams, useLocation } from 'react-router-dom';

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

  // 原history.push('/list') 对应写法
  const goToList = () => navigate('/list');
  // 原history.replace('/detail') 对应写法
  const redirectToDetail = () => navigate('/detail', { replace: true });
  // 获取路由参数id
  const id = params.id;

  return <div>当前路由:{location.pathname}</div>
};

export default MyComponent;

场景2:项目使用类组件(无法使用Hooks)

自行实现一个兼容的 withRouter 高阶组件即可,用法和v5版本完全一致:

// 新建自定义withRouter工具文件
import { useNavigate, useParams, useLocation } from 'react-router-dom';

export function withRouter(Component) {
  function WrappedComponent(props) {
    const navigate = useNavigate();
    const params = useParams();
    const location = useLocation();
    // 将路由相关能力挂载到props.router上,也可以根据使用习惯直接展开到props
    return <Component {...props} router={{ navigate, params, location }} />;
  }
  return WrappedComponent;
}

使用示例:

import { withRouter } from './utils/withRouter';

class MyClassComponent extends React.Component {
  render() {
    const { navigate, params, location } = this.props.router;
    return <div>路由参数id:{params.id}</div>
  }
}

export default withRouter(MyClassComponent);
注意事项

React Router v6 已废弃原 history 对象,所有跳转操作统一使用 navigate 方法:

  • 页面前进/后退:navigate(1) / navigate(-1)
  • 携带state跳转:navigate('/path', { state: { id: 1 } })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:06:03