dva中組件的懶加載

組件的按需加載是提升首屏性能的重要手段。

[email protected]使用了[email protected],相關的使用方式有變化,網上的討論基本上都是舊的,不清楚的話會比較亂,這裏做一下記錄。

[email protected]以前

[email protected]以前的懶加載相關討論有不少,可以參考dva-example-user-dashboard中的寫法,徐飛大佬的文章使用 Dva 開發複雜 SPA,本質上藉助的是webpack的require.ensure實現代碼分割,參考代碼分割 - 使用 require.ensure
具體實現形如:

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

[email protected]以後

[email protected]使用了[email protected],其中的路由是組件式的,原來的方式就不太好搞。因此dva提供了一個dynamic函數來處理。
[email protected]發佈日誌dva api文檔中有介紹。
具體實現形如:

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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章