React Router Dom v6 类组件如何获取history对象,withRouter导入报错怎么解决
问题原因
React Router v6 版本官方直接移除了 v5 中提供的 withRouter 高阶组件,所以无论你安装 react-router 还是 react-router-dom 都无法导入该 API,属于版本迭代的正常变更,不是依赖安装问题。
解决方案
方案1:自定义 withRouter 高阶组件(适配类组件,改动最小)
你可以自行封装和 v5 功能一致的 withRouter 高阶组件,通过 v6 提供的原生 Hook 把路由相关属性注入到类组件的 props 中:
你可以新建单独的 withRouter.js 公共文件,也可以直接在你的类组件文件顶部添加如下代码:
import { useNavigate, useLocation, useParams } from 'react-router-dom' function withRouter(Component) { function ComponentWithRouterProp(props) { const navigate = useNavigate(); const location = useLocation(); const params = useParams(); return ( <Component {...props} // 完全对齐v5的history用法 history={{ push: navigate, go: (n) => navigate(n), goBack: () => navigate(-1), goForward: () => navigate(1) }} location={location} match={{ params }} /> ); } return ComponentWithRouterProp; }
之后把你原本从 react-router 导入 withRouter 的代码,替换为导入你自己封装的这个 withRouter 即可,原有类组件的逻辑不需要做任何调整,就可以正常通过 this.props.history 调用相关路由能力。
方案2:重构为函数组件(官方推荐)
如果组件改动成本不高,可以直接改为函数组件,直接使用 v6 原生提供的 Hook 实现需求:
import React from 'react' import { useNavigate, useLocation, useParams } from 'react-router-dom' const Blog = () => { // 等价于v5中withRouter注入的history相关能力 const navigate = useNavigate() const location = useLocation() const params = useParams() // 用法示例: // navigate('/target-path') 等价于 history.push('/target-path') // navigate(-1) 等价于 history.goBack() console.log({navigate, location, params}) return ( <div> <h4>History</h4> </div> ) } export default Blog
对应路由配置不需要修改,直接把原有的 <B/> 替换为 <Blog/> 即可正常运行。
内容的提问来源于stack exchange,提问作者mrhrifat
相关产品推荐
相关产品推荐

