使用 react-router 从路径确定 locationKey

Determine locationKey from path with react-router

假设我有这样的路由配置:

<Router>
  <Route path="/" component={App}>
    <Route path="about" component={About} />
    <Route path="inbox" component={Inbox}>
      <Route path="messages/:id" component={Message} />
    </Route>
  </Route>
</Router>

并假设当前 url 是:/inbox/messages/6

假设每个组件的 locationKeys 如下:

/ = "loc1" (as accessed in App component as this.props.location.key)
/inbox = "loc2"
/messages/:id = "loc3"

无论如何,我可以要求 react-router 给我给定路由路径的位置键吗?例如我想传入 "messages/:id" 并返回 "loc3"

或者,我是否可以获得对当前在该路径上呈现的 React 组件的引用? IE。如果我传入 "messages/:id" 我会取回当前显示消息 ID 6 的 Message 实例?

如果你去/messages/123然后去/inbox再去/messages/123,第二次访问消息的key是不同的,所以,没有。

关键通常不是相关的东西,你要location.state.

获取组件,嗯,你就是组件,所以thisthis.props.children