Advanced use of react router

Use objects instead of JSX to configure routes

Once written:

<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Dashboard} />
    <Route path="about" component={About} />
    <Route path="inbox" component={Inbox}>
      <Route path="/messages/:id" component={Message} />

      {/* Jump to / inbox/messages/:id to / messages/:id */}
      <Redirect from="messages/:id" to="/messages/:id" />
    </Route>
  </Route>
</Router>

Advanced usage:

const routeConfig = [
  { path: '/',
    component: App,
    indexRoute: { component: Dashboard },
    childRoutes: [
      { path: 'about', component: About },
      { path: 'inbox',
        component: Inbox,
        childRoutes: [
          { path: '/messages/:id', component: Message },
          { path: 'messages/:id',
            onEnter: function (nextState, replaceState) {
              replaceState(null, '/messages/' + nextState.params.id)
            }
          }
        ]
      }
    ]
  }
]

React.render(<Router routes={routeConfig} />, document.body)

Dynamic routing

Route can define getChildRoutes, getIndexRoute and getComponents. They are all executed asynchronously and only called when needed. We call this approach "gradual matching.". React Router will gradually match the URL and only load the path configuration and components required by the corresponding page of the URL.

When overriding routerConfig, you need to change the component to getComponent.

const routeConfig = {
  path: '/',
  indexRoute: {
    getComponent(nextState, cb) {
      require.ensure([], (require) => {
        cb(null, require('components/layer/HomePage'))
      }, 'HomePage')
    },
  },
  getComponent(nextState, cb) {
    require.ensure([], (require) => {
      cb(null, require('components/Main'))
    }, 'Main')
  },
  childRoutes: [
    require('./routes/baidu'),
    require('./routes/404'),
    require('./routes/redirect')
  ]
}

The getComponent method is asynchronous, that is, it is called only when the route matches.

The require.ensure method is provided by webpack, which is also the core method of on-demand loading. The first parameter is dependency, and the second is callback function.

Tags: React Webpack

Posted on Fri, 01 May 2020 13:33:25 -0700 by mickfuzz