React 中动态路由与静态路由的优势 [英] Advantages of dynamic vs static routing in React

查看:197
本文介绍了React 中动态路由与静态路由的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 React Router 中的 静态路由与动态路由,以及我正在努力确定后者的优势(以及为什么 v4 选择使用它).我可以看到列出应用程序的所有路由(静态)以及每个路由映射到的组件的优势,允许您跟踪给定特定 URL 将呈现的内容.但我没有看到动态路由的任何明显优势.

如果有的话,我只能看到缺点,因为没有明确的方法来查看 URL 将映射到什么状态,而无需从根应用程序元素开始并通过路由(尽管我可能会误会).

动态路由寻址什么情况?为什么它比静态路由更可取(可能特别是在 React 应用中)?

解决方案

动态路由

来自反应路由器文档:

<块引用>

当我们说动态路由时,我们的意思是作为您的路由发生应用正在呈现,而不是在一个配置或约定之外运行应用.

将路由视为组件

react-router (pre v4) 的早期版本曾经有静态路由.这导致到应用中的集中式路由,例如:

<路由器><Route path='/' component={Main}><IndexRoute 组件={Home}/><Route path='about' component={About}/><Route onEnter={verifyUser} path='profile' component={Profile}/>...</路线></路由器>

然而,这并不完全是 React 的做事方式.React 专注于使用基于组件的逻辑进行组合.因此,与其将我们的 Route 想象成一个静态系统,我们还可以将它们想象成一个组件,这就是 react-router v4 所带来的及其背后的主要理念.

因此,我们可以像使用任何 React 组件一样使用 Route.这让我们可以在构建不同组件时添加 Route 组件.这样做的一个好处是我们可以将路由逻辑与需要它们的组件分离.

嵌套路由

About 组件可以处理所有路由,并根据 url(比如 /about/job/about/life 等).

另一件需要注意的事情是 Route 组件要么为匹配的路由渲染组件,要么为 null 渲染.例如,下面的 Route 渲染路由 /aboutnull (或什么都没有)的 About 组件.

这也类似于我们在 React 中使用条件渲染组件的方式:

route === '/about' ?<关于/>: 空值

现在,如果我们需要在 About 组件中为路由 /about/job/about/life 渲染一些其他组件,我们可以这样做:

const About = ({ match ) =>(<div>...<路由路径={`${match.url}/job`} component={Job}/><路由路径={`${match.url}/life`} component={Life}/>

)

动态导入和代码拆分

就我个人而言,我还发现这种方法更适合我,以防我使用带有代码拆分的动态导入,因为我可以在我的任何组件中添加动态路由.例如,

import Loadable from 'react-loadable';常量加载 = () =>(<div/>);const 作业 = 可加载({加载器:() =>导入('./作业'),加载:加载,});const Life = Loadable({加载器:() =>进口('./生活'),加载:加载,});...使成为() {返回 (...<路由路径={`${match.url}/job`} component={Job}/><路由路径={`${match.url}/life`} component={Life}/>)}

响应式路由

动态路由的另一个很好的用例是创建响应式路由,这在 反应路由器文档 和推荐阅读.这是文档中的示例:

const App = () =>(<应用布局><Route path="/invoices" component={Invoices}/></AppLayout>)const 发票 = () =>(<布局>{/* 始终显示导航 */}<发票导航/><媒体查询={PRETTY_SMALL}>{screenIsSmall =>屏幕小//小屏幕没有重定向?<开关><路由精确路径="/invoices/dashboard" component={Dashboard}/><Route path="/invoices/:id" component={Invoice}/></开关>//大屏幕!:<开关><路由精确路径="/invoices/dashboard" component={Dashboard}/><Route path="/invoices/:id" component={Invoice}/><Redirect from="/invoices" to="/invoices/dashboard"/></开关>}</媒体></布局>)

总结文档,您会发现它是多么简单并且声明性地使用动态路由将 Redirect 添加到大屏幕尺寸.在这种情况下使用静态路由会非常麻烦,并且需要我们将所有路由放在一个地方.动态路由简化了这个问题,因为现在逻辑变得可组合(就像组件一样).

静态路由

有些问题是动态路由不容易解决的.静态路由 的一个优点是它允许检查和匹配路由在渲染之前.因此它被证明在服务器端尤其有用.React 路由器团队也在研究一个名为 react- 的解决方案路由器配置,引用自:

<块引用>

随着 React Router v4 的引入,不再有集中路由配置.有一些用例是了解应用的所有潜在路线很有价值,例如:

  1. 在渲染下一个屏幕之前在服务器上或生命周期中加载数据
  2. 按名称链接到路线
  3. 静态分析

希望这能很好地总结动态路由和静态路由以及它们的用例:)

I'm reading about static vs dynamic routing in React Router, and I'm struggling to identify the advantages of the latter (and why v4 chose to go with it). I can see the advantage of listing out all the routes for an application (static), as well as the component that each route maps to, allowing you to trace what would be rendered given a specific URL. But I'm not seeing any clear advantage to dynamic routes.

If anything, I can only see disadvantages, because there is no clear way to see what state a URL will map to, without starting at the root app element and working your way through the routes (though I might be mistaken).

What situations does dynamic routing address? Why is it preferable to static routing (maybe specifically in React apps)?

解决方案

Dynamic Routing

From the react router docs:

When we say dynamic routing, we mean routing that takes place as your app is rendering, not in a configuration or convention outside of a running app.

Think of routes as components

The earlier versions of react-router (pre v4) used to have static routes. This led to a centralized routing in apps like:

<Router>
    <Route path='/' component={Main}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route onEnter={verifyUser} path='profile' component={Profile} />
      ...
    </Route>
</Router>

However, this is not exactly the React way of doing things. React focuses on composition using components based logic. So, instead of imagining our Routes as a static system, we can imagine them as components, which is what react-router v4 brings in and the primary philosophy behind it.

Therefore, we can use Route as we would use any React component. This lets us add Route components as and when we build different components. One advantage of doing this is we can decouple the routing logic to the components needing them.

Nesting routes

The About component can handle all the routes and conditionally render parts of UI based on the url (say /about/job or /about/life etc).

Another thing to note is that a Route component will either render the component for a matching route or null. Example, the following Route renders the About component for a route /about and null (or nothing) otherwise.

<Route path='about' component={About} />

This is also similar to how we're used to conditionally rendering components in React:

route === '/about' ? <About /> : null

Now if we need to render some other components inside the About component for routes /about/job or /about/life we can do it like:

const About = ({ match ) => (
    <div>
        ...
        <Route path={`${match.url}/job`} component={Job} />
        <Route path={`${match.url}/life`} component={Life} />
    </div>
)

Dynamic imports and code splitting

Personally, I've also found this approach works better for me in case I'm using dynamic imports with code-splitting, since I can add dynamic routes in any of my components. For example,

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} />
    )
}

Responsive routes

Another great use case for dynamic routing is creating responsive routes which is explained beautifully in the react router docs and a recommended read. Here's the example from the 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>
)

Summarizing the docs, you'll notice how simple and declarative it becomes to add the Redirect to large screen sizes using dynamic routing. Using static routing in such cases would be quite cumbersome and would need us to put all the routes in a single place. Having dynamic routing simplifies this problem since now the logic becomes composable (like components).

Static Routing

There are some problems which are not solved easily with dynamic routing. An advantage of static routing is that it allows for inspection and matching of routes before rendering. Hence it proves useful especially on server side. The react router team is also working on a solution called react-router-config, quoting from which:

With the introduction of React Router v4, there is no longer a centralized route configuration. There are some use-cases where it is valuable to know about all the app's potential routes such as:

  1. Loading data on the server or in the lifecycle before rendering the next screen
  2. Linking to routes by name
  3. Static analysis

Hope this provides a good summary of both Dynamic Routing and Static Routing and the use cases for them :)

这篇关于React 中动态路由与静态路由的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆