IndexRoute sub-routes

IndexRoute sub-routes

本文关键字:sub-routes IndexRoute      更新时间:2023-09-26

我有一个网站,只有几个普通页面,还有一个带有谷歌地图的页面。单击地图标记时,带有标记详细信息的面板将显示在地图旁边。这个细节有自己的URL,用户可以链接到它:

<Route path="/" component={App}>
    <IndexRoute component={Welcome} />
    <Route path="map" component={Map}>
        {/* Detail is a child component of Map,
            it only adds detail panel markup to Map.  */}
        <Route path="detail/:id" component={Detail} /> 
    </Route>
    <Route path="about" component={About} />
</Route>

这很好用。但是,让我们去掉欢迎页面,并在web根上显示地图,这样:
/渲染App > Map组件
/detail/:id渲染App > Map > Detail组件
/about渲染App > About组件

<Route path="/" component={App}>
    {/* Map has to be IndexRoute so that it is displayed at root URL. */}
    <IndexRoute component={Map}>
        <Route path="detail/:id" component={Detail} /> 
    </IndexRoute>
    <Route path="about" component={About} />
</Route>

但这不起作用,因为IndexRoute不能有子例程。

这是我找到的最好的解决方案:

<Route path="/" component={App}>
    <Route component={Map}>
        <IndexRoute component={EmptyComponent} />
        <Route path="detail/:id" compoent={Detail} />
    </Route>
    <Route path="about" component={About} />
</Route>

但我不喜欢空的组件。

我是不是错过了什么?我在做什么不寻常的事吗?为什么不可能用第一种更直观的方式来做呢?

移动/路径

<Route component={App}>
  <Route path="/" component={Map}>
    <Route path="detail/:id" component={Detail}/>
  </Route>
  <Route path="/about"/>
</Route>

您的解决方案对我来说基本上很好——唯一需要注意的是,在这种情况下您不需要指定组件;只需执行<IndexRoute />

按照设计,索引路由终止匹配,但插入琐碎的路由很容易。

也许我错了,但似乎你试图在中设置另一条路线

<IndexRoute component={Map}>
   <Route path="detail/:id" component={Detail} /> 
</IndexRoute>

所以你的基本结构是这样的:

<IndexRoute> <Route> </Route> </IndexRoute>

根据您的错误,您的<IndexRoute>内部不允许有<Route>。。。一开始你没有犯那个错误,因为你在打开下一个<Route>-Tag之前关闭了<IndexRoute>

因此,如果您想让代码再次工作,就不应该在<IndexRoute>中打开另一个<Route>。您通过添加一个Dummy IndexRoute成功修复了此问题。因此,如果您想将Map组件设置为IndexRoute,则必须更改HTML结构,以便在Map组件中没有Detail组件,因为这样您将再次遇到与<IndexRoute> 中有<Route>相同的问题