Skip to content

[业务产出] react lazy load with retry #45

@PeterChen1997

Description

@PeterChen1997

react 组件异步加载过程中,可能会由于页面部署原因导致 chunk 加载失败,从而导致整体页面报错,此处加上自动刷新页面的功能,可以解决此问题

同时可以让本地开发的过程中更加顺畅

import React, { lazy } from 'react';

const BASE_REFRESH_KEY = 'FORCE_REFRESH_KEY';

// Inspired by: https://raphael-leger.medium.com/react-webpack-chunkloaderror-loading-chunk-x-failed-ac385bd110e0
const lazyWithRetry = (key: string, componentImport: Parameters<typeof lazy>[0]) =>
  lazy(async () => {
		const forceRefreshKey = BASE_REFRESH_KEY + key
    const pageHasAlreadyBeenForceRefreshed = JSON.parse(
      window.localStorage.getItem(forceRefreshKey) || 'false',
    );

    const hardReload = () => {
      const url = window.location.href;

      window.location.href = url;
    };

    try {
      const component = await componentImport();

      window.localStorage.setItem(forceRefreshKey, 'false');

      return component;
    } catch (error) {
      if (!pageHasAlreadyBeenForceRefreshed) {
        window.localStorage.setItem(forceRefreshKey, 'true');
        hardReload();

        return {
          default() {
            return <>reloading</>;
          },
        };
      }

      throw error;
    }
  });

export default lazyWithRetry;

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions