【问题标题】:React router v4 nested route relative pathReact router v4 嵌套路由相对路径
【发布时间】:2017-11-09 15:31:46
【问题描述】:

我有一个带有反应路由器 v4 的组件到另一个组件,我想在第二个组件中添加另一个路由。

这是主要路线:

const Dashboard = () => {
  return (
    <div>
      <Header/>
      <Router>
        <div>
          <Route path="/" exact component={Wall} />
          <Route path="/challenge/:id" component={Challenge} />
        </div>
      </Router>
    </div>
  )
}

这是挑战组件:

class Challenge extends Component {
  ...

  render() {
    return (
      ...
        <Router>
          <div>
            <Route path="/overview" exact component={Overview} />
            <Route path="/discussions" exact component={Discussions} />
          </div>
        </Router>
      ...
    )
  }
}

这对我不起作用..

唯一可行的选择是将 /challenge/:id 包含在挑战组件中:

<Route path="/challenge/:id/overview" exact component={Overview} />
<Route path="/challenge/:id/discussions" exact component={Discussions} />

最后我想让路线看起来像这样,例如:

www.site.com/challenge/1/overview

www.site.com/challenge/1/discussions

但不包含每个嵌套路由中的完整路由。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    在你的 Challenge 组件中试试这个:

    class Challenge extends Component {
      ...
    
      render() {
        const { match } = this.props;
        return (
          ...
          <div>
            <Route path={`${match.url}/overview`} exact component={Overview} />
            <Route path={`${match.url}/discussions`} exact component={Discussions} />
          </div>
          ...
        )
      }
    }
    

    请注意,您不需要添加新的 Router 实例,因为您的 Challenge 组件是您在* Dashboard 组件中定义的 Router 实例的后代。

    【讨论】:

    • match.path 应该用于&lt;Route/&gt;s 而match.url 应该用于&lt;Link/&gt;s
    • 注意math.url中的斜杠