gpt4 book ai didi

reactjs - React lazy 不会导致成 block 拆分包

转载 作者:行者123 更新时间:2023-12-04 13:43:35 25 4
gpt4 key购买 nike

如标题所示,我正在尝试使用 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 中执行此操作。

我在这里缺少什么?

最佳答案

我也有同样的问题,后来我解决了这个案例不使用悬念和懒惰(尝试下面的代码) ,我可以看到块文件。但是,使用这种方式后,我再次尝试使用 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} />

关于reactjs - React lazy 不会导致成 block 拆分包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com