【问题标题】:How to get current route from outside in react-router?如何在 react-router 中从外部获取当前路由?
【发布时间】:2016-11-27 12:35:15
【问题描述】:

是否可以从外部组件获取当前路由?

基本上,我有一个仅显示当前页面标题的页面标题组件。似乎无法弄清楚如何从外部组件访问路由?

编辑: App.jsx

<div style={styles.container}> <Sidebar style={styles.sidebar} links={sidebarLinks}/> <div style={styles.wrapper}> <Header style={styles.header}/> <div style={styles.content}> <PageTitle style={styles.pageTitle} /> //Want current route here {this.props.children} </div> <Footer style={styles.footer}/> </div> </div> 路线

    const routes =  (
<Route path="/" component={App}>
    <IndexRoute component={Dashboard}></IndexRoute>
    <Route path="containers" component={Containers} />
    <Route path="discover" component={Discover} />
    <Route path="groups" component={Groups} />
    <Route path="profiles" component={Profiles} />
</Route>
);

【问题讨论】:

  • 不确定您的确切意思,但不妨看看这个? github.com/nfl/react-helmet
  • @zackify 请参阅编辑。基本上,我没有添加到页面标题组件的路由,因为它只是所有页面的页面标题。
  • 啊,我明白了。更好的方法是将&lt;PageTitle /&gt; 组件放在特定页面上。另一种方式,但不是那么好:React 路由器会将路由对象注入到您的顶级组件中,您可以执行routes[routes.length -1] 之类的操作来获取我认为匹配的最后一条路由。
  • @zackify 你说把 组件放在特定页面上是什么意思?你是说在路线上?你能给我举个例子吗?
  • 打开ContainersDiscover等。将页面标题放在每个组件上。

标签: reactjs routes react-router params


【解决方案1】:

不知道你在问什么。也许你可以使用window.location API:

window.location.href

window.location.pathname

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2018-08-01
    • 2016-05-04
    • 2016-12-29
    • 2021-05-21
    • 2022-01-02
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多