动态路由
来自反应路由器docs:
当我们说动态路由时,我们指的是作为您的路由发生的
应用正在呈现,而不是在 a 之外的配置或约定中
正在运行的应用程序。
将路由视为组件
react-router(pre v4)的早期版本曾经有静态路由。这导致
到应用程序中的集中路由,例如:
<Router>
<Route path='/' component={Main}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route onEnter={verifyUser} path='profile' component={Profile} />
...
</Route>
</Router>
然而,这并不完全是 React 的做事方式。 React 专注于使用基于组件的逻辑进行组合。因此,与其将我们的 Routes 想象成一个静态系统,我们可以将它们想象成组件,这就是 react-router v4 带来的东西,也是它背后的主要理念。
因此,我们可以像使用任何 React 组件一样使用Route。这让我们可以在构建不同组件时添加Route 组件。这样做的一个好处是我们可以将路由逻辑与需要它们的组件解耦。
嵌套路线
About 组件可以处理所有路由并根据 url 有条件地渲染部分 UI(例如 /about/job 或 /about/life 等)。
要注意的另一件事是Route 组件将呈现该组件以匹配路由或null。例如,下面的Route 为路由/about 和null(或没有)渲染About 组件。
<Route path='about' component={About} />
这也类似于我们在 React 中用于有条件地渲染组件的方式:
route === '/about' ? <About /> : null
现在,如果我们需要在 About 组件内为路由 /about/job 或 /about/life 渲染一些其他组件,我们可以这样做:
const About = ({ match ) => (
<div>
...
<Route path={`${match.url}/job`} component={Job} />
<Route path={`${match.url}/life`} component={Life} />
</div>
)
动态导入和代码拆分
就我个人而言,我还发现这种方法更适合我使用带有代码拆分的动态导入,因为我可以在我的任何组件中添加动态路由。例如,
import Loadable from 'react-loadable';
const Loading = () => (
<div />
);
const Job = Loadable({
loader: () => import('./Job'),
loading: Loading,
});
const Life = Loadable({
loader: () => import('./Life'),
loading: Loading,
});
...
render() {
return (
...
<Route path={`${match.url}/job`} component={Job} />
<Route path={`${match.url}/life`} component={Life} />
)
}
响应式路由
动态路由的另一个很好的用例是创建响应式路由,在 react router docs 和推荐阅读中有很好的解释。这是文档中的示例:
const App = () => (
<AppLayout>
<Route path="/invoices" component={Invoices}/>
</AppLayout>
)
const Invoices = () => (
<Layout>
{/* always show the nav */}
<InvoicesNav/>
<Media query={PRETTY_SMALL}>
{screenIsSmall => screenIsSmall
// small screen has no redirect
? <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
</Switch>
// large screen does!
: <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
<Redirect from="/invoices" to="/invoices/dashboard"/>
</Switch>
}
</Media>
</Layout>
)
总结docs,您会注意到使用动态路由将Redirect 添加到大屏幕尺寸变得多么简单和声明性。在这种情况下使用静态路由会非常麻烦,并且需要我们将所有路由放在一个地方。动态路由简化了这个问题,因为现在逻辑变得可组合(就像组件一样)。
静态路由
有些问题是动态路由不容易解决的。 static routing 的一个优点是它允许在渲染之前检查和匹配路线。因此它被证明是有用的,尤其是在服务器端。 React 路由器团队也在研究一个名为 react-router-config 的解决方案,引用自:
随着 React Router v4 的引入,不再有
集中路由配置。有一些用例
了解应用程序的所有潜在路线很有价值,例如:
- 在渲染下一个屏幕之前在服务器上或生命周期中加载数据
- 按名称链接到路线
- 静态分析
希望这可以很好地总结动态路由和静态路由以及它们的用例:)