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

React Router v6中withRouter的等效替代方案是什么?

React Router v6 中 withRouter 的替代方案

React Router v6 已移除 withRouter 高阶组件,官方推荐使用内置的路由 Hooks 来获取路由相关状态。根据你的组件类型,有两种可行方案:

1. 若 Main 是函数组件

直接在 Main 组件内部使用路由 Hooks(如 useLocation、useNavigate、useParams)获取所需的路由属性,无需再用 withRouter 包裹:

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

function Main() {
  // 获取路由相关状态
  const location = useLocation();
  const navigate = useNavigate();
  const params = useParams();

  // 按业务需求使用上述对象,例如:
  // navigate('/target-path') 替代 history.push
  // location.pathname 获取当前路径

  return <div>...</div>;
}

// 原导出逻辑移除 withRouter
export default connect(mapStateToProps)(withI18n(Main));

2. 若 Main 是类组件

如果不想将类组件转为函数组件,可以自行封装一个类似 withRouter 的高阶组件,通过 Hooks 获取路由属性后传递给类组件:

封装自定义 withRouter HOC

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

const withRouter = (Component) => {
  const WithRouterWrapper = (props) => {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();

    // 传递路由属性给原组件
    return (
      <Component
        {...props}
        location={location}
        navigate={navigate}
        params={params}
        // 若需要 match 对象,可使用 useMatch,注意 v6 中 useMatch 需要传入路径参数
        // match={useMatch('/your-path/:param')}
      />
    );
  };

  return WithRouterWrapper;
};

使用自定义 withRouter

保持和原代码类似的导出结构即可:

export default connect(mapStateToProps)(withI18n(withRouter(Main)));

注意事项

  • v6 中 navigate 函数替代了 v5 的 history.push/history.replace,用法为 navigate('/new-path') 或 navigate(-1) 返回上一页;
  • useParams 直接返回路由参数对象,替代了 v5 中 match.params;
  • 若需使用 match 对象,useMatch 需传入具体路径(如 useMatch('/users/:id')),返回匹配信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:25:29