问题:‘withRouter’ is not exported from 'react-router-dom
原因:“react-router-dom”: “^6.2.1” 版本升级
目的:实现命令式跳转,V5:history.push(‘xxxx’)
解决方式一:
- 用钩子写withRouter函数,utils/withRouter.js
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
export default function withRouter(Component) {
function ComponentWithRouterProp(props) {
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
- 导入使用命名为withRouter,按照原本用法
import withRouter from '../utils/withRouter'
withRouter(Xxcomponent)
- Xxcomponent内获取router,可以使用navigate实现history效果
const Xxcomponent= ({router: {location,navigate,params } }) => {}
//跳转到xxxx
navigate('xxxx')
解决方式二:
更简单做法:直接使用钩子,不使用withRouter
例如:
1. import { useNavigate } from 'react-router-dom'
2. const navigate = useNavigate();
3. navigate('xxxx')