【发布时间】:2018-09-11 20:27:24
【问题描述】:
来自 React Router 的 docs:
<Switch>的所有子元素都应该是<Route>或<Redirect>元素。只有第一个匹配当前位置的子节点才会被渲染。
尽管如此,嵌套的<Switch> 语句是允许的。我使用该模式分解大量<Routes>:
<Switch>
<Route path="/foo" component={FooRouter} />
<Route path="/bar" component={BarRouter} />
<Route path="/baz" component={BazRouter} />
</Switch>
...
const FooRouter = () => (
<Switch>
<Route exact path="/foo/:id" component={ViewFoo} />
<Route exact path="/foo/new" component={NewFoo} />
</Switch>
)
const BarRouter = () => (
<Switch>
<Route exact path="/bar/new" component={NewBar} />
</Switch>
)
....
想知道是否有更好的方法来分解大量路由以及是否应该避免嵌套的<Switch> 语句?
【问题讨论】:
-
您开始提问时的引述解决了我的问题。在对 React 有用的建议和警告感到高兴之后,在使用其他库时仅仅因为您不记得文档而出现问题是很痛苦的。
标签: react-router react-router-v4 react-router-dom