【问题标题】:How to properly use nested routes with react-router?如何正确使用带有 react-router 的嵌套路由?
【发布时间】:2016-07-22 04:22:38
【问题描述】:

我试图在/dashboard 路径下使用 react-router 获得嵌套 UI,所以我得到了:

<Route
  path={'/dashboard'}
  component={Components.Dashboard}
  onEnter={utils.onlyAfterLogin}>

  <Route
    path={'/tiendas'}
    component={Components.StoresIndex} />

</Route>

我希望 '/dashboard' 成为具有自己 UI 内容的父路由,并包含呈现为嵌套路径的嵌套 UI。所以'/dashboard/tiendas' 应该渲染仪表板的东西以及Components.StoresIndex 组件。

当我尝试访问'/dashboard/tiendas'时,它会抛出一个警告日志:

warning: [react-router] Location "/dashboard/tiendas" did not match any routes

Dashboard 的东西渲染得很好,这就是 Dashboard 组件的样子(只显示渲染方法):

  render () {
    return (
      <div>
        <AppBar
          title="Distribuidores Movistar"
          onLeftIconButtonTouchTap={() => {this.setState({leftNavOpen:true})}}
          iconElementRight={
            <IconMenu
              iconButtonElement={
                <IconButton><MoreVertIcon /></IconButton>
              }
              targetOrigin={{horizontal: 'right', vertical: 'top'}}
              anchorOrigin={{horizontal: 'right', vertical: 'top'}}
            >
              <MenuItem primaryText="Cerrar sessión" />
            </IconMenu>
          }
        />
        <LeftNav open={this.state.leftNavOpen}>
          <MenuItem>Ventas</MenuItem>
          <MenuItem>Inventario</MenuItem>
          <MenuItem>Usuarios</MenuItem>
          <MenuItem>Tiendas</MenuItem>
          <MenuItem>Configuraciones</MenuItem>
          <Divider/>
          <FloatingActionButton mini={true} style={{marginRight: 20}}>
            <ContentAdd />
          </FloatingActionButton>
        </LeftNav>
        <Link to={'/dashboard/tiendas'}>Akira</Link>
        {this.props.children}
      </div>
    );
  }

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    假设您使用的是最新的 react-router 版本(在撰写本文时为 2.0.1),这就是它的使用方式。 除非它是最顶层的路由组件,否则您不需要在路由前加上 '/'。

    <Route path="/" component={Root}>
      <Route path="dashboard" component={Dashboard}>
        <Route path="tiendas" component={Tiendas}/>
      </Route>
    </Route>
    

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2019-05-30
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多