根据React-Router文档:
当我们说动态路由时,我们指的是在您的应用呈现时发生的路由,而不是在正在运行的应用之外的配置或约定中 . 这意味着几乎所有东西都是React Router中的一个组件 .
很清楚,在您的应用程序开始时,所有路由都没有初始化,
在 React-router v3 或以下,它使用 static Routes 并且所有路由将在顶层初始化,并且嵌套过去就像
通过这个API设置,react-router重新实现了React(生命周期等)的部分,并且它与React建议使用的组合逻辑不匹配 .
通过动态路线,可以预见到以下优点
Nested Routes
具有动态路由的嵌套路由更像
const App = () => (
{/* here's a div */}
{/* here's a Route */}
)
// when the url matches `/todos` this component renders
const Todos = ({ match }) => (
// here's a nested div
{/* here's a nested Route,
match.url helps us make a relative path */}
path={`${match.path}/:id`}
component={Todo}
/>
)
在上面的示例中,仅当/ todos与route-path匹配时,才会挂载Todo组件,然后才会定义Route路径 /todos/:id .
Responsive routes
React-router docs有一个很好的用例 .
考虑用户导航到 /invoices . 您的应用适用于不同的屏幕尺寸,它们具有较窄的视口,因此您只需向其显示发票列表和发票的链接 dashboard . 他们可以更深入地导航那里 .
但是,在大屏幕上,导航位于左侧,仪表板或特定发票显示在右侧 .
因此 /invoices 不是大屏幕的有效路线,我们希望重定向到 /invoices/dashboard . 这可能发生,用户从 portait to a landscape mode 旋转他/她的手机 . 这可以使用动态路由轻松完成
const Invoices = () => (
{/* always show the nav */}
{screenIsSmall => screenIsSmall
// small screen has no redirect
?
// large screen does!
:
}
)
使用带有React Router的动态路由,请考虑 components ,而不是静态路由 .
Code Splitting
网络的一个重要特点是我们不必让访问者在使用它之前下载整个应用程序 . 您可以将代码拆分视为逐步下载应用程序 . This is made possible with Dynamic Routing .
它带来的好处是不需要立即下载所有代码,因此它可以使初始渲染更快 .
Here 是一篇很好的文章,可以帮助您为您的应用程序设置代码分割
Writing Composable Authenticated Routes
使用动态路由,它还可以更容易地编写PrivateRoutes(进行身份验证的HOC),允许对用户进行身份验证并为他们提供对特定路由的访问权限,否则将重定向 . 这个叫我所有人都非常一般
典型的私人路线看起来像
const PrivateRoute = ({ component: Component, ...rest }) => (
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
) : (
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
并可以用作