如何正确使用react-router的嵌套路由?

die*_*lar 0 javascript reactjs react-router

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

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

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

</Route>
Run Code Online (Sandbox Code Playgroud)

我想'/dashboard'成为一个父路由,它有自己的UI东西,并包括呈现为嵌套路径的嵌套UI.所以'/dashboard/tiendas'应该渲染仪表板的东西和Components.StoresIndex组件.

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

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

仪表板的东西渲染得很好,这就是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>
    );
  }
Run Code Online (Sandbox Code Playgroud)

Igo*_*ton 5

这是应该如何使用,假设你使用最新的react-router版本(写这篇文章时的2.0.1).除非它是最顶层的路由组件,否则您不需要使用'/'为路由添加前缀.

<Route path="/" component={Root}>
  <Route path="dashboard" component={Dashboard}>
    <Route path="tiendas" component={Tiendas}/>
  </Route>
</Route>
Run Code Online (Sandbox Code Playgroud)