react-router-dom v6导入withRouter提示未导出的替换实现方法
react-router-dom v6替换withRouter解决方案
该报错是由于react-router-dom v6已经正式移除
withRouter高阶组件,官方不再导出该API,可通过以下两种方案实现原有功能:
方案1:直接使用路由Hooks改造(函数组件推荐)
你的代码本身是函数组件,直接使用v6提供的useNavigate即可实现原有跳转逻辑,无需使用HOC包裹,改造后完整代码如下:
import { useNavigate } from 'react-router-dom' const MenuItem =({title,imageUrl,size,linkUrl})=>{ const navigate = useNavigate() return ( <div className={`${size} menu-item`} onClick={()=> navigate(linkUrl)} > <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
v6的navigate默认支持相对路径跳转,传入非/开头的路径时会自动拼接在当前路由路径后,和原有${match.url}${linkUrl}的跳转效果完全一致。
方案2:自定义withRouter高阶组件(兼容类组件/原有逻辑复用)
如果你需要兼容类组件,或者不想改动原有组件的props逻辑,可以自行封装一个withRouter,实现和v5版本一致的能力:
// 自定义withRouter.js文件 import { useNavigate, useParams, useLocation } from 'react-router-dom' export function withRouter(Component) { return function WrappedComponent(props) { const navigate = useNavigate(); const params = useParams(); const location = useLocation(); // 模拟v5版本的history、match、location对象 return <Component {...props} history={{ push: navigate, replace: (path) => navigate(path, {replace: true}), goBack: () => navigate(-1) }} match={{params, url: location.pathname}} location={location} /> } }
使用时将原有import { withRouter } from 'react-router-dom'替换为导入你封装的withRouter即可,其余原有代码无需改动。
核心API对应关系
- 原
history.push(path)→navigate(path) - 原
history.replace(path)→navigate(path, {replace: true}) - 原
history.goBack()→navigate(-1) - 原
match.params→useParams()返回值 - 原
location对象 →useLocation()返回值
内容的提问来源于stack exchange,提问作者wahid_ull_islam
相关产品推荐
相关产品推荐

