使用React.lazy与Webpack动态导入?

Gambit2007

我想知道使用“声明”动态导入之间的区别是什么React.lazy()

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

或使用webpack的动态导入(如此处所述)进行操作:https ://webpack.js.org/guides/code-splitting/#dynamic-imports

(就我而言,我正打算在webpack中捆绑)

费利克斯莫什

React.lazy获取一个返回Promise的回调,并返回一个可渲染的组件。

Webpacks动态导入返回一个Promise,该承诺将在加载块时解决,因此,您不能直接呈现它。

您可以重新实现React.lazy功能,这实际上是基本的实现。

class SomeComponent extends React.Component {
  state = {LazyComponent: null};

  async componentDidMount() {
    const LazyComponent = await import('./path/to/LazyComponent');
    this.setState({LazyComponent});
  }
  render() {
    const {LazyComponent} = this.state;
    return LazyComponent ? <LazyComponent {...props} /> : null;
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章