如何使用react-router基于路由呈现容器/组件?

时间:2016-12-16 00:44:42

标签: reactjs react-router

我的routes.jsx看起来像

return (
  <Route path='/' component={Main}>
    <IndexRoute
      component={Home}
      onEnter={onSearchEnter}
      onChange={(prevState, nextState) => onSearchEnter(nextState)}
    />

    <Route path='privacy' component={Privacy} />
    <Route path='terms' component={Terms} />
    <Route path='dmca' component={DMCA} />

    <Route path='clips/:clip' component={Clip} />
  </Route>
)

在我的Main中,我有类似的内容:

  render () {
    return (
      <div className={`main__container ${get(this, 'props.children.type.parentClassName')}`}>
        {(() => {
          return (
            <Nav
              downloadLinks={this.props.downloadLinks}
              search={this.props.search}
            />
          )
        })()}

但是,如果我在Nav路线中,我不想呈现clips/:clip组件。

我正在使用react-router

1 个答案:

答案 0 :(得分:2)

您应该使用react-router传递给您的主容器的位置道具。

它是一个可以找到当前路径名的对象。我做这样的事情:

isNavVisible = (location) => {
   return location.pathname.split('/')[1] !== 'clips';
   // location.pathname would be '/clips/someClipID'
   // => location.pathname.split('/') would be ["", "clips", "someClipID"]
}

render () {
  return (
  <div className={`main__container ${get(this, 'props.children.type.parentClassName')}`}>
    {this.isNavVisible(this.props.location) &&
      <Nav
        downloadLinks={this.props.downloadLinks}
        search={this.props.search}
      />
    }
   ...
}