Front-end routing Settings usually fall into two categories:

Centrally configured routing

This is also used most often in the early days, as in:

{
  "routes": [{"path": "/"."component": "./a"},
    {"path": "/list"."component": "./b"."Routes": ["./routes/PrivateRoute.js"] {},"path": "/users"."component": "./users/_layout"."routes": [{"path": "/users/detail"."component": "./users/detail"},
        {"path": "/users/:id"."component": "./users/id"}]}]}Copy the code

There are even frameworks that fuse routing and request data, such as:

const Routes = [
  {
    path: '/'.exact: true.component: Home,
  },
  {
    path: '/posts'.component: Posts,
    loadData: (a)= > loadData('posts'),}, {path: '/todos'.component: Todos,
    loadData: (a)= > loadData('todos'),}, {component: NotFound,
  },
];
Copy the code

Are relatively simple example above, the path is used and the business logic in a real project, get the data and front-facing dependence and conflict, and considering the routing permissions, logic reuse, modular, routing, guardian, conditional, etc., let the centralized configuration routing overwhelmed, to write to the configuration file behind who all look not to understand.

Dynamic component routing

A typical example is the React-Router, which disperses the routing logic among various components into a special routing component. The component dynamically generates routing rules while running in its life cycle. Such as:

<Switch>
  <Route exact path="/admin/home" component="{AdminHome}" />
  <Route exact path="/admin/role/:listView" component="{AdminRole}" />
  <Route path="/admin/member/:listView" component="{AdminMember}" />
</Switch>
Copy the code

This way routing and business logic is distributed among related components, effectively breaking down the complexity of centralized configuration. It looks elegant, but it also presents some new problems:

  • First, the routing becomes obscure and unintuitive, making it more difficult to modify and change
  • By binding routes to components, render is no longer pure and contains side effects of the external environment
  • Hard-coding the path into the component is not conducive to late modification
  • As a string, path loses type inference and checking
  • For redirects and so on, you have to dynamically execute it later to realize that it is equal to the front but rendering is wasted
  • Finally, this approach is difficult to cross platform and framework, for example, it cannot be applied to the server rendering SSR, and it cannot be applied to some environments that do not support dynamic components, such as: applets, VUE, etc

Explore better routing schemes

Since centralized configuration and dynamic component routing each have advantages and disadvantages, is there a better way to merge the two? In fact, their biggest problem is that routing takes on too many functions (routing, data fetch, business logic, permissions, daemons, component life cycle…).

Return to the essence of routing:

  • Internally: Routing is nothing more than an application providing a way to save a slice of a recording application’s perspective. For single-page applications without routes, the entire application has only one slice. The more routing rules are defined, the more internal slices can be displayed by the system. So routing is a state that records the state of the application.

  • From the outside: Routing is simply an application providing a way for the outside world (users) to request access to which views. From this point of view, a route simply carries two pieces of information:

    • Request which views to display. That’s the view name
    • How to present them. That is, show the parameters they need to provide

After we extract these two pieces of information in the route, we directly inject them into our state management, so that the function of the route is also completed, the next thing is the state management, has nothing to do with the route.

For example, for a URL:

/admin/role/list? q={adminRole: {title:"medux", page: 1, pageSize: 20}}#q={adminRole: {_random: 34532324}}
Copy the code

We can extract this information from the middle and inject it into redux:

{
  "views": {
    "app": {"Main": true},
    "adminLayout": {"Main": true},
    "adminRole": {"List": true}},"paths": ["app.Main"."adminLayout.Main"."adminRole.List"]."params": {
    "app": {},
    "adminLayout": {},
    "adminRole": {
      "listView": "list"."title": "medux"."page": 1."pageSize": 20."sortBy": "createTime"."_random": 34532324}}}Copy the code

Route stateful

Think of routing as a state of application like Redux. Except that Redux is recorded in memory and maintained by the user through interface interaction, while Route is recorded in the browser address bar and maintained by the user through manual input, they are essentially the same.

So there is no routing after converting the route to the state. In the component you directly control the display of the state view:

<Switch> {routeViews.adminHome? .Main && <AdminHome />} {routeViews.adminRole? .List && <AdminRole />} {routeViews.adminMember? .List && <AdminMember />} </Switch>Copy the code

conclusion

After the above simplification of routing functions, routing logic becomes a thin layer. Do we still need react-router? Do you still need a routing component? What more bikes? Less complicated mental burden, just go back to simple MVVM, expressed in an abstract formula:

  • State = Combine(Route)
  • UI = Render(State)

In fact, the routing logic still exists, but it is transferred from the Router to the state management, cutting off the direct connection between the router and the Component, and becoming the router and the state management directly, because the state is more concise than the UI and does not have so many life cycles, and we directly have mature MVVM solutions to use. So you can reduce the complexity

And then finally, the problem is, even though routing has become a single function, it still has to perform a function, so how do you make routing state? How do you extract from a string of URL characters what views to show and what parameters to pass?

Of course, you can design your own routing scheme. I also designed one: @medux/ Route-plan-a. You can check out my open source framework: Medux

Medux framework introduction

The above only represents personal exploration, welcome to clap brick exchange

[6/16] Add:

Route is not to decide good at the beginning, very likely at the beginning of the business what route all do not require, you do a single page on the line, the back of the discovery with not comfortable (how a refresh on the home page? Can I send the current URL to the client? Can I keep my current search criteria? All of a sudden you have a routing control, and when you have routing state management, you just put the control parameters into the route by state management, and the lower layer stays the same.

For example, I used to play window is controlled by state management, can business said via the URL can pop up actively, below is the Demo, can online preview: medux-react-admin.80zp.com/admin/membe…