先使用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組件.
.