banner
leoking

leoking

前端开发者
tg_channel

umi Dynamic Loading Demo

When using umi for dynamic loading, it is often necessary to load code blocks for components or pages to improve the performance of the application through code splitting and lazy loading. Here are some code solutions for implementing dynamic loading in umi:

  1. Using umi's dynamic method:

Using umi's setTimeout method, components can be loaded on demand. This method can delay the loading of components until after the page is rendered, reducing the loading time of the application. Here is an example code for dynamically loading components using the first method:

import { dynamic } from 'umi';

export default function Example() {
  const [visible, setVisible] = useState(false);

  function handleClick() {
    setVisible(true); // Display the loaded component when clicked
  }

  const AsyncComponent = dynamic({
    loader: async function() {
      const { default: MyComponent } = await import('./MyComponent');
      return MyComponent;
    },
  });

  return (
    <div>
      <button onClick={handleClick}>Load component</button>
      {visible && <AsyncComponent />}
    </div>
  );
}
  1. Using React.lazy and Suspense:

React.lazy was introduced in React 16.6 and it can quickly achieve lazy loading, and it is very convenient to use. Here is an example code for dynamically loading components using React.lazy and Suspense:

import React, { useState, Suspense } from 'react';

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

export default function Example() {
  const [visible, setVisible] = useState(false);

  function handleClick() {
    setVisible(true); // Display the loaded component when clicked
  }

  return (
    <div>
      <button onClick={handleClick}>Load component</button>
      {visible && (
        <Suspense fallback={<div>Loading...</div>}>
          <MyComponent />
        </Suspense>
      )}
    </div>
  );
}

These are two commonly used methods for dynamically loading components in umi. When using these methods, it is important to note that when loading components on demand, some components need to be loaded before they can be displayed. In this case, the React.Suspense component should be used to display the loading state and ensure the normal rendering process of the component.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.