Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dva中组件的懒加载 #9

Closed
javanli opened this issue Jul 6, 2020 · 0 comments
Closed

dva中组件的懒加载 #9

javanli opened this issue Jul 6, 2020 · 0 comments

Comments

@javanli
Copy link
Owner

javanli commented Jul 6, 2020

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

dva@2.0使用了react-router@4.0,相关的使用方式有变化,网上的讨论基本上都是旧的,不清楚的话会比较乱,这里做一下记录。

dva@2.0以前

dva@2.0以前的懒加载相关讨论有不少,可以参考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} />;
}

dva@2.0以后

dva@2.0使用了react-router@4.0,其中的路由是组件式的,原来的方式就不太好搞。因此dva提供了一个dynamic函数来处理。
dva@2.0发布日志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;
@javanli javanli closed this as completed Sep 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant