【问题标题】:Accessing this.props.location.pathname within the Route component在 Route 组件中访问 this.props.location.pathname
【发布时间】:2017-07-17 13:41:18
【问题描述】:

在我有<Route> 代码的 SideMenuNavigation 组件上,我需要访问this.props.location.pathname 的值。不幸的是,我收到了undefined

class SideNavigation extends React.Component {

  componentDidMount() {
    console.log(this.props.location.pathname); // undefined
  }

  render() {
    return(
     <Router>
       <Route exact path="/" component={Dashboard}/>
     </Router>
    )
  }
}


/*   */

在我的仪表板组件中,我可以成功访问this.props.location.pathname。不幸的是,我不需要这个组件。我需要SideMenuNavigation 组件中的值。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    location 是 Router 组件注入的 props 之一。在您的情况下, SideNavigation 不是路由器组件的子组件(实际上它是父组件)。你可能也对这个问题感兴趣:How does react-router pass params to other components via props?

    【讨论】:

    • 我使用 withRouter 和 pathless 让它工作了,所以export default withRouter(SideNavigation) 它已经修复了! :)
    猜你喜欢
    • 2016-11-22
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-06-30
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多