我将首先将我所做的研究联系起来 .
-
Why can I not nest Route components in react-router 4.x? - Question
-
React Router v4入门 - 流星厨师
-
警告:你不应该使用和使用相同的路线;
<Route children>
将被忽略 - teamtreehouse
对不起看起来我只能发布2个外部链接 .
TL; DR
我在React Router 4中找到了2种嵌套方法,每种方法都有它的优点和缺点 .
-
首先 . 这是
react-router
的团队推荐方式,优点是Route
组件是他们加载的地方,但我发现很难跟踪路由 . -
第二 . 以某种方式管理在一个地方进行所有路由,但是有一些重复的代码和一个不必要的嵌套级别,通过添加一个帮助组件,我也不确定是否可以这样做 .
所以这些是我发现嵌套的两种方式 . 我在找:
-
任何人发现做路线嵌套的任何其他方式 .
-
我该怎样嵌套?你认为哪种方式最好?
从这项研究中我've found two ways to do the nesting, I' m与 react-router-dom
合作 .
1.反应路由器文档推荐方式
因此,根据React Router,在同一个文件上执行所有路由都已结束,因此现在应该通过将嵌套路由放在组件中来完成嵌套 .
import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topics = () => (
<div>
<Route path="/topics/topic" component={Topic}/>
</div>
)
const Topic = () => (
<div>
<h2>One Topic</h2>
</div>
)
const BasicExample = () => (
<Router>
<div>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
export default BasicExample
2.将它们放在一个地方 .
环顾四周,人们已经找到了在一个文件中完成所有路由的方法,比如在我引用的其中一个链接上,但它有一些缺点,例如,使用"Not Found"页面需要使用 Switch
组件,这是很好,但是如果你嵌套你会遇到一些问题,比如必须重复代码 . 例如,这可行 .
2.1第一级嵌套
const MainLayout = ( {children} ) => (
<div>
<h2>Main Layout</h2>
{children}
</div>
);
const Home = () => (
<div>
<h2>Home</h2>
</div>
);
const About = () => (
<div>
<h2>About</h2>
</div>
);
const FirstLevelNesting = () => (
<Router>
<MainLayout>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route component={NoMatch}/>
</Switch>
</MainLayout>
</div>
</Router>
);
export default FirstLevelNesting;
2.2二级嵌套
在这里你可以看到如何使用辅助组件在第二级进行嵌套,你不能像在第一级那样进行嵌套,方法是将 MainLayout
之类的组件放在 Switch
中,因为当 Switch
到达它时,它将会总是匹配路径,我们永远不会得到 NotFound
,这就是为什么我们需要使用辅助组件来进行嵌套,然后再次在该组件内部我们还需要添加 NotFound
.
const NestedRoutes = () => (
<div>
<h2>This is my next nest</h2>
<Switch>
<Route exact path='/nextnest' component={Nest}/>
<Route path='/nextnest/about' component={NestAbout}/>
<Route component={NoMatch}/>
</Switch>
</div>
)
const SecondLevelNesting = () => (
<Router>
<MainLayout>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/nextnest" component={NestedRoutes}
<Route component={NoMatch}/>
</Switch>
</MainLayout>
</div>
</Router>
);