react-router 4.x 和 5.x 获取当前的路由地址的区别

react-router 4.x 和 5.x 获取当前的路由地址的区别,第1张

一、react-router 4.x

先使用withRouter对组件进行装饰
然后就可以使用this.props.location.pathname获取到了

使用@withRouter语法不支持的话使用export default withRouter(App)

import React from 'react';
import { withRouter } from 'react-router-dom';

@withRouter
export default class App extends React.Component {
    //...
    getPathname = () => {
        console.log(this.props.location.pathname);
    }
    //...
}
二、react-router 5.x
import { useLocation } from 'react-router-dom'

function Breadcrumb() {
  const location = useLocation();
  console.log(location.pathname);
  return (Path : {location.pathname});
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1297931.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-10
下一篇2022-06-10

发表评论

登录后才能评论

评论列表(0条)

    保存