先使用withRouter
对组件进行装饰
然后就可以使用this.props.location.pathname
获取到了
例如:
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); } //... }
使用@withRouter语法不支持的话使用export default withRouter(App),如下所示
import { Link, withRouter } from 'react-router-dom'
//组件内容...
export default withRouter(LeftNav);
详见文章浅谈react传入路由参数---withRouter组件.
.