Lazy loading of components in dva

Keywords: Javascript React Webpack

On demand loading of components is an important means to improve the performance of the first screen.

dva@2.0 uses react router @ 4.0. There are changes in the way it is used. Online discussions are basically old. If it is unclear, it will be messy. Here is a record.

Before dva@2.0

There are many discussions about lazy loading before dva@2.0. Please refer to dva-example-user-dashboard The way of writing in, Xu Fei's article Developing complex SPA with Dva In essence, it implements code segmentation with the help of webpack's require.ensure Code segmentation - use require.ensure.
The specific implementation form is as follows:

function RouterConfig({ history, app }) {
  const routes = [
    {
      path: '/',
      name: 'IndexPage',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          registerModel(app, require('./models/dashboard'));
          cb(null, require('./routes/IndexPage'));
        });
      },
    },
    {
      path: '/users',
      name: 'UsersPage',
      getComponent(nextState, cb) {
        require.ensure([], (require) => {
          registerModel(app, require('./models/users'));
          cb(null, require('./routes/Users'));
        });
      },
    },
  ];

  return <Router history={history} routes={routes} />;
}

After dva@2.0

dva@2.0 uses react router @ 4.0, in which the routing is component-based, and the original way is not easy to handle. Therefore, dva provides a dynamic function to handle.
stay dva@2.0 publishing log and dva api documentation There is an introduction in.
The specific implementation form is as follows:

import dynamic from 'dva/dynamic';

function RouterConfig({ history,app }) {
  const UserPageComponent = dynamic({
    app,
    models: () => [
      import('./models/users'),
    ],
    component: () => import('./routes/UserPage'),
  });
  return (
    <Router history={history}>
      <Switch>
        <Route path="/user" component={UserPageComponent} />
        <Route component={IndexPageComponent} />
      </Switch>
    </Router>
  );
}
export default RouterConfig;

Posted by loweauto on Tue, 03 Dec 2019 12:27:54 -0800