使用params反应路由器4嵌套路由

时间:2017-10-05 20:47:55

标签: reactjs react-router

我很难理解如何使用react路由器4在下面的设置中添加文档路由。也许uuid需要作为propPage传递给DocumentsPage,以便您可以返回DocumentPage?

routes = {
    home: '/',
    documents: '/documents',
    createDocument: '/documents/create',
    document: '/document/:uuid',
}

<BrowserRouter>
    <div>
        <Switch>
            <Route exact={true} path={routes.home} component={HomePage} />
            <Route path={routes.documents} component={DocumentsPage} />
            <Route path={routes.createDocument} component={CreateDocumentPage} />
            <Route component={NotFoundPage} />
        </Switch>
    </div>
</BrowserRouter>

1 个答案:

答案 0 :(得分:0)

小麦退回@ mikkel在评论中的建议,请尝试以下方法:

routes = {
  home: '/',
  documents: '/documents',
  createDocument: '/documents/create',
  document: '/document/:uuid',
};

<BrowserRouter>
  <div>
    <Switch>
      <Route exact path={routes.home} component={HomePage} />
      <Route exact path={routes.createDocument} component={CreateDocument} />
      <Route path={routes.document} component={Document} />
      <Route path={routes.documents} component={DocumentsPage} />
      <Route component={NotFoundPage} />
    </Switch>
  </div>
</BrowserRouter>

在这种情况下,它会首先查找/documents/create完全匹配,然后是document/:uuid,最后是/documents

获取uuid组件中的<Document />将位于this.props.match.params.uuid