React Lazy不会导致捆绑拆分

时间:2018-11-07 09:25:25

标签: reactjs lazy-loading

与标题中一样,我正在尝试使用React.lazy功能,该功能可以在我的其他项目中使用。但不是在这一本书中,我不知道我在这里缺少什么。一切正常,没有错误,没有警告。但是由于某种原因,我看不到我的捆绑包分成几块。

这是我的实现方式

import React, { Component, Suspense } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { getApps } from '../../actions/apps';
import './_apps.scss';

const AppItemComponent = React.lazy(() => import('../AppItem'));

class Apps extends Component {
  componentDidMount() {
    const { getApps } = this.props;

    getApps(3);
  }

  renderAppItem = () => {
    const { apps } = this.props;

    return apps && apps.map((item, i) =>  {
      return (
        <Suspense fallback={<div>loading...</div>} key={i}>
          <AppItemComponent
            index={i + 1}
            item={item}
          />
        </Suspense>
      );
    });
  };

  render() {
    const { apps } = this.props;

    return (
      <div className="apps__section">
        <div className="apps__container">
          <div className="apps__header-bar">
            <h3 className="apps__header-bar--title">Apps</h3>
            <Link className="apps__header-bar--see-all link" to="/apps">{`see all (${apps.length})`}</Link>
          </div>
          {this.renderAppItem()}
        </div>
      </div>
    );
  }
}

const mapStateToProps = ({ apps }) => {
  return { apps };
};

const mapDispatchToProps = dispatch => {
  return {
    getApps: quantity => dispatch(getApps(quantity)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Apps);

我正在react-create-app应用程序和react v16.6,react-dom v16.6中进行此操作。

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

我也有同样的问题,然后我解决了这个案例没有使用 Suspense 和 lazy(尝试下面的代码),我可以看到块文件。但是,使用这种方式后,我再次尝试使用 Suspense 和 lazy 更改我的代码。有用!!!我不知道为什么会这样。希望它适用于有人为这种情况找到解决方案。

1 - 创建文件 asyncComponent

import React, { Component } from "react";

const asyncComponent = (importComponent) => {
   return class extends Component {
      state = {
         component: null,
      };

      componentDidMount() {
         importComponent().then((cmp) => {
            this.setState({ component: cmp.default });
         });
      }

      render() {
         const C = this.state.component;

         return C ? <C {...this.props} /> : null;
      }
   };
};

export default asyncComponent;

2 - 在 App.js 中,例如:

const AuthLazy = asyncComponent(() => import("./containers/Auth/Auth"));
//Route
<Route path="/auth" component={AuthLazy} />