了解React Router嵌套子路由

时间:2018-07-09 15:16:32

标签: javascript reactjs react-router

我正在尝试使用嵌套路由来构建应用程序,但是我正努力从子页面转到其父页面。应用程序的大致布局:

Navbar
- '/' -Home
- '/templates' - Templates
-- '/templates/{id} - View
--- '/templates/{id}/edit - Edit

在Home和Templates之间切换很容易,从Edit到Home也可以。但是,从“编辑”转到“模板”将导致/ templates / {id} / templates的URL。

我的应用程序的大致布局:

<Nav> 
  <Main>
    <Templates>
      <DataTable />
      <Edit />
    </Templates>
  </Main> 
</Nav>

主要包括以下开关:

<Switch>
  <Route exact path='/' component={Home} />
  <Route path='/templates' component={Templates} />
  <Route component={NotFound} />
</Switch>

Nav包含以这种方式构建的链接:

class DrawerLink extends React.Component {
  renderLink = itemProps => <Link to={this.props.link} {...itemProps} />;

  render() {
    const { display } = this.props;
    console.log(this.props.link);
    return (
        <ListItem button component={this.renderLink}>
            <ListItemText primary={display} />
        </ListItem>
    );
  }
}

模板组件随后包含此开关:

<Switch>
  // Gets a query component which then renders DataTable
  <Route exact path={`${props.match.url}`} component={GetTemplates} />
  // View will go here once it is built
  // Gets a query component which then renders Edit
  <Route exact path={`${props.match.url}/:templateId/edit`} component={GetTemplate} />
</Switch>

DataTable还包含转到“编辑”页面的链接,该链接的构建方式与Nav中的链接相同。

1 个答案:

答案 0 :(得分:1)

导航到“模板”将导致在当前网址中添加“ / templates”:

eg. www.example.com/templates/1/edit -> www.example.com/templates/1/edit/templates

导航到“ /模板”将导致从域更改网址:

eg. www.example.com/templates/1/edit -> www.example.com/templates
相关问题