动态路由
从反应路由器文档:
当我们说动态路由时,我们指的是在您的应用程序渲染时发生的路由
,而不是在正在运行的应用程序之外的配置或约定中。
将路由视为组件
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 带来的内容以及它背后的主要理念。
因此,我们可以Route
像使用任何 React 组件一样使用。这让我们可以Route
在构建不同组件时添加组件。这样做的一个好处是我们可以将路由逻辑与需要它们的组件解耦。
嵌套路线
该About
组件可以处理所有路由并根据 url(比如等)有条件地渲染 UI 的/about/job
一部分/about/life
。
另一件需要注意的事情是,一个Route
组件要么为匹配的路由渲染该组件,要么为null
. 例如,以下Route
渲染About
路由的组件,/about
否则null
(或不渲染)。
<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>
)
总结一下文档Redirect
,您会注意到使用动态路由将其添加到大屏幕尺寸变得多么简单和声明性。在这种情况下使用静态路由会非常麻烦,并且需要我们将所有路由放在一个地方。拥有动态路由简化了这个问题,因为现在逻辑变得可组合(如组件)。
静态路由
有一些问题是动态路由不容易解决的。静态路由的一个优点是它允许在渲染之前检查和匹配路由。因此它被证明是有用的,尤其是在服务器端。react 路由器团队也在研究一个名为react-router-config的解决方案,引用其中:
随着 React Router v4 的引入,不再有集中的路由配置。在一些用例中,了解应用程序的所有潜在路线很有价值,例如:
- 在渲染下一个屏幕之前在服务器上或生命周期中加载数据
- 按名称链接到路线
- 静态分析
希望这可以很好地总结动态路由和静态路由以及它们的用例:)