10 异步组件

  • import()
  • React.lazy
  • React.Suspense

何时使用异步组件

  • 加载大组件
  • 路由懒加载
    import React from 'react'
    
    const ContextDemo = React.lazy(() => import('./ContextDemo'))
    
    class App extends React.Component {
        constructor(props) {
            super(props)
        }
        render() {
            return <div>
                <p>引入一个动态组件</p>
                <hr />
                <React.Suspense fallback={<div>Loading...</div>}>
                    <ContextDemo/>
                </React.Suspense>
            </div>
    
            // 1. 强制刷新,可看到 loading (看不到就限制一下 chrome 网速)
            // 2. 看 network 的 js 加载
        }
    }
    
    export default App

react router如何配置懒加载

补充(现代做法):函数组件下更推荐 const ContextDemo = lazy(() => import('./ContextDemo')) 配合 <Suspense fallback={...}> 直接使用(无需 React. 前缀)。React 18 起 Suspense 不再只用于代码分割,还能配合支持 Suspense 的数据请求方案(如 React Query、SWR、RSC、use())做「数据级」加载态。SSR 场景下 React 18 的 renderToPipeableStream + <Suspense> 支持选择性注水(selective hydration)与流式渲染。

Last Updated:
Contributors: leeguooooo