Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
PeterChen1997 opened this issue Jul 18, 2022 · 0 comments
Open

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

PeterChen1997 opened this issue Jul 18, 2022 · 0 comments

Comments

@PeterChen1997
Copy link
Owner

PeterChen1997 commented Jul 18, 2022

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;
@PeterChen1997 PeterChen1997 changed the title [业务产出] react lazy load with retry - doing [业务产出] react lazy load with retry Jul 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant