ReactRouterV6获取当前路由参数

1.由于v6把旧版本中的路由组件能收到的三个参数(Location,history,match)移除了,所以不能直接使用this.props.location.pathname获取到当前路由。而且withRouter也移除了
2.在v6获取当前路由,需要自己定义withRouter,代码如下

  • withRouter.js
import {useLocation, useNavigate } from "react-router";  
import React from 'react'
export default function withRouter(Child) {
    return (props) => {
        const location = useLocation();
        const navigate = useNavigate();
        return <Child {...props} navigate={navigate} location={location} />;
    }
}

3.在此使用写好的withRouter,按如下方式使用

import React, { Component } from 'react'
import withRouter from '../../utils/withRouter'  //在此引入自己的文件所在路径
 class index extends Component {
    render() {
       //能够调用到了
        console.log(this.props.location)
        return (
            <div>
            </div>
        )
    }
}
export default withRouter(index)

4.结果如下(按自己需要获取即可):
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐