React 路由器 - 嵌套路由不起作用
React router - Nested routes not working
我的目标是让 http://mydomain/route1 render React component Component1 and http://mydomain/route2 呈现 Component2。所以,我认为像下面这样写路由是很自然的:
<Route name="route1" handler={Component1}>
<Route name="route2" handler={Component2} />
</Route>
<DefaultRoute name="home" handler={Home} />
</Route>
http://mydomain/route1 works as expected but http://mydomain/route2 渲染 Component1。
然后我阅读了this question并将路由更改为如下:
<Route name="route1" path="route1" handler={Component1} />
<Route name="route2" path="route1/route2" handler={Component2} />
<DefaultRoute name="home" handler={Home} />
</Route>
两个 http://mydomain/route2 and http://mydomain/route2 现在都按预期工作。但是,我不明白为什么前一个在我看来更合乎逻辑和整洁的情况下不起作用。
嵌套语法适用于“/”和 "route1" 那么为什么 "route1" 和 "route2" 不行呢?
问题是在嵌套路由中,路由器会尝试挂载所有符合层次结构的组件。当你想将组件相互嵌套时,最好使用它......但是如果你想要两个单独的路由来匹配不同的组件,它们将需要是它们自己的路由。
<Route handler={App}>
<Route path="route1" handler={Component1} />
<Route path="/route1/route2" handler={Component2} />
<DefaultRoute name="home" handler={Home} />
</Route>
Component2
将在 URL 为 /route1/route2
时挂载(在 App
内部)。
如果您想嵌套组件,您需要将 <RouteHandler/>
添加到 Component1
,以便它在其中呈现 Component2
。
之所以可行,是因为嵌套组件与嵌套 URL 不同,可以由路由器单独处理。有时您希望组件嵌套但不一定是 URL,反之亦然。
在导航需要正确活动状态的地方使用分层路由时,更好的方法是执行以下操作(使用 RR2 的语法):
<Route path="route1">
<IndexRoute component={Component1}/>
<Route path="route2" component={Component2} />
</Route>
这样,当 URL 为 /route1/route2
时,route1
的任何导航链接都将正确地处于活动状态。
我正在解决类似的问题(Component2
未呈现)并且嵌套路由无法正常工作,因为我忘记在 Component1
中呈现 {this.props.children}
我的目标是让 http://mydomain/route1 render React component Component1 and http://mydomain/route2 呈现 Component2。所以,我认为像下面这样写路由是很自然的:
<Route name="route1" handler={Component1}>
<Route name="route2" handler={Component2} />
</Route>
<DefaultRoute name="home" handler={Home} />
</Route>
http://mydomain/route1 works as expected but http://mydomain/route2 渲染 Component1。
然后我阅读了this question并将路由更改为如下:
<Route name="route1" path="route1" handler={Component1} />
<Route name="route2" path="route1/route2" handler={Component2} />
<DefaultRoute name="home" handler={Home} />
</Route>
两个 http://mydomain/route2 and http://mydomain/route2 现在都按预期工作。但是,我不明白为什么前一个在我看来更合乎逻辑和整洁的情况下不起作用。
嵌套语法适用于“/”和 "route1" 那么为什么 "route1" 和 "route2" 不行呢?
问题是在嵌套路由中,路由器会尝试挂载所有符合层次结构的组件。当你想将组件相互嵌套时,最好使用它......但是如果你想要两个单独的路由来匹配不同的组件,它们将需要是它们自己的路由。
<Route handler={App}>
<Route path="route1" handler={Component1} />
<Route path="/route1/route2" handler={Component2} />
<DefaultRoute name="home" handler={Home} />
</Route>
Component2
将在 URL 为 /route1/route2
时挂载(在 App
内部)。
如果您想嵌套组件,您需要将 <RouteHandler/>
添加到 Component1
,以便它在其中呈现 Component2
。
之所以可行,是因为嵌套组件与嵌套 URL 不同,可以由路由器单独处理。有时您希望组件嵌套但不一定是 URL,反之亦然。
在导航需要正确活动状态的地方使用分层路由时,更好的方法是执行以下操作(使用 RR2 的语法):
<Route path="route1">
<IndexRoute component={Component1}/>
<Route path="route2" component={Component2} />
</Route>
这样,当 URL 为 /route1/route2
时,route1
的任何导航链接都将正确地处于活动状态。
我正在解决类似的问题(Component2
未呈现)并且嵌套路由无法正常工作,因为我忘记在 Component1
{this.props.children}