Advantages of dynamic vs static routing in React

。_饼干妹妹 提交于 2019-12-02 18:14:31

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 :)

According to 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. That means almost everything is a component in React Router.

Its clear for the explanation that, all you Routes are not initialised at the start of your application,

In React-router v3 or below, it used static Routes and all Routes would be initialised at the top level, and nesting used to be achieved like

<Router>
    <Route path='/' component={App}>
      <IndexRoute component={Dashboard} />
      <Route path='users' component={Users}>
          <IndexRoute component={Home}/>
          <Route path="users/:id" component={User}/> 
      </Route>
    </Route>
</Router>

With this API setup, react-router was reimplementing parts of React (lifecycles, and more), and it just didn’t match the composition logic that React recommends on using.

With Dynamic Routes the following advatages, comes to be foreseen

Nested Routes

Nested Routes with Dynamic Routing are more like

const App = () => (
    <BrowserRouter>
        {/* here's a div */}
        <div>
        {/* here's a Route */}
        <Route path="/todos" component={Todos}/>
        </div>
    </BrowserRouter>
)

// when the url matches `/todos` this component renders
const Todos  = ({ match }) => (
    // here's a nested div
    <div>
        {/* here's a nested Route,
            match.url helps us make a relative path */}
        <Route
        path={`${match.path}/:id`}
        component={Todo}
        />
    </div>
)

In the above example, only when /todos matches the route-path, the Todo component is mounted and only then the Route path /todos/:id is defined.

Responsive routes

The React-router docs have a good use case for this.

Consider a user navigates to /invoices. Your app is adaptive to different screen sizes, they have a narrow viewport, and so you only show them the list of invoices and a link to the invoice dashboard. They can navigate deeper from there.

However on a large screen, navigation is on the left and the dashboard or specific invoices show up on the right.

and hence /invoices is not a valid Route for a large screen and we would want to redirect to /invoices/dashboard. This may so happen, the user rotates his/her phone from a portait to a landscape mode. This can easily be done using dynamic Routing

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

Using Dynamic Routes with React Router’s, think about components, not static routes.

Code Splitting

One great feature of the web is that we don’t have to make our visitors download the entire app before they can use it. You can think of code splitting as incrementally downloading the app. This is made possible with Dynamic Routing.

The advantages it brings is that all your code need not be downloaded at once and hence it makes initial rendering faster.

Here is a good article that helps you setUp codeSplitting for your application

Writing Composable Authenticated Routes

With Dynamic Routing its also made easier to write PrivateRoutes(an HOC that does authentication) which allow for authenticating users and providing them access to specific Routes and redirecting otherwise. This call all me made very generically

A Typical Private Route would be look like

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

and can be used as

<PrivateRoute path="/protected" component={Protected} />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!