react中如何正确使用懒加载?

react项目为了做性能优化减小包体积在项目中用了大量的React.lazy加载组件进行代码分割,效果也挺明显,包大小从1.4M缩小到110KB但是到生产后监控到通过React.Lazy这种方式加载组件会有失败的场景(走到了代码的catch)。请问下这种场景页面是不是会报错白屏(复现不出来不知道现象是怎么样的)

请问各位大佬这种情况该怎么处理啊?添加重试功能?
还是像官方的处理一样添加ErrorBoundary

const ModuleA = React.lazy(() => {
    return new Promise((resolve: any, reject) => {
        import('moduleWrap')
            .then(module => {
                resolve(module)
            })
            .catch(err => {
                /****/
            })
    })
})
阅读 2.1k
1 个回答

用 Error Boundaries 和重试:

import React, { Component, lazy, Suspense } from 'react';

// Error Boundary
class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // log the error to an error reporting service
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

// Retry logic
function withRetry(importPromise) {
  let retryCount = 0;
  function tryImport() {
    return importPromise().catch(error => {
      if (retryCount < 3) {
        retryCount++;
        return tryImport();
      }
      throw error;
    });
  }
  return tryImport();
}

// Lazy load the component
const LazyComponent = lazy(() => withRetry(() => import('./LazyComponent')));

// Use the lazy component
function MyComponent() {
  return (
    <ErrorBoundary>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </ErrorBoundary>
  );
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题