React路由器将当前活动的段作为参数获取

时间:2017-01-27 05:52:06

标签: javascript reactjs react-router

我有以下路由器配置

<Router history={history}>
    <Route path="/" component={ReviewWizard}>
        <IndexRoute component={Administrative}/>

        <Route path="Administrative" component=Administrative}>
            <Route path="/Administrative/:itemId" component={AdministrativeItem}/>
        </Route>
        <Route path="Offense" component={Offense}/>
    </Route>
</Router>

我正在尝试获取当前有效的路线段(即AdministrativeOffense)。

有没有办法做这样的事情?即路线约束

<Router history={history}>
    <Route path="/:segment" component={ReviewWizard}>
        <IndexRoute component={Administrative}/>

        <Route path="/:segment=Administrative/:itemId" component={Administrative}>
            <Route path="/Administrative/:itemId" component={AdministrativeItem}/>
        </Route>
        <Route path="/:segment=Offense" component={Offense}/>
    </Route>
</Router>

如果没有,获取当前活动路径段的最佳做法是什么?我不喜欢this.context.router.routes[1].path

1 个答案:

答案 0 :(得分:1)

首先,我会推荐以下路由器配置,因为它似乎是您的目标:

<Router history={history}>

  <Route path="/" component={ReviewWizard}>

    <!-- whenever we hit '/' we redirect to '/Administrative' -->
    <IndexRedirect path="/Administrative"/>

    <!-- Renders ReviewWizard <- Administrative -->
    <Route path="/Administrative" component={Administrative}>

      <!-- Renders ReviewWizard <- Administrative <- AdministrativeItem -->
      <Route path="/Administrative/:itemId" component={AdministrativeItem}/>

    </Route>

    <!-- Renders ReviewWizard <- Offense -->
    <Route path="/Offense" component={Offense}/>

  </Route>

</Router>

至于检测当前活动的路由(或路由片段是否处于活动状态),我建议使用the router.isActive -method。简单地做这样的事情:

if (router.isActive('/Administrative')) {
  doSomething()
} else if (router.isActive('/Offense')) {
  doSomethingElse()
}

对于更具说明性的内容,我建议只使用the location object react-router注入其管理的每个组件:

const { location: { pathname } } = this.props
const [ activeSegment ] = pathname.slice(1).split('/')

希望这些帮助!