lazy內置方法 Suspense內置組件
-
lazy是React提供的懶(動態)加載組件的方法,
React.lazy()
-
能減少打包體積、延遲加載首屏不需要渲染的組件
-
依賴內置組件Suspense:給lazy加上loading指示器組件的一個容器組件
-
Suspense目前只和lazy配合實現組件等待加載指示器的功能
-
React.lazy 接受一個函數,這個函數需要動態調用 import()。它必須返回一個 Promise,該 Promise 需要 resolve 一個 default export 的 React 組件。所以要用類返回render而不是函數
-
index.jsx
import Loading from './loading'
const MyMain = React.lazy(() => import('./main.jsx'))
function App() {return (<div>{/* 注意 fallback這里是組件 */}<React.Suspense fallback={<Loading />}><MyMain /></React.Suspense></div>)
}ReactDOM.render(<App />,document.getElementById('app')
)
- main.jsx
// export function Main() {
// return (
// <div>
// 顯示內容
// </div>
// )
// }
// React.lazy 接受一個函數,這個函數需要動態調用 import()。
// 它必須返回一個 Promise,該 Promise 需要 resolve 一個 default export 的 React 組件。
export default class Main extends React.Component {render() {return (<div>顯示內容</div>)}
}
- Loading.jsx
export default function Loading() {return (<div><h1>Loading...</h1><h1>Loading...</h1><h1>Loading...</h1></div>)
}
路由懶加載
yarn add react-router react-router-dom
- 本地調試時,path和文件名同名,會變成訪問文件
- index.jsx
import Loading from './loading'
import React, { lazy, Suspense } from 'react'
import { BrowserRouter } from 'react-router-dom'
import { Switch, Route } from 'react-router'
const MyMain = lazy(() => import('./main.jsx'))
function App() {return (<div>{/* 注意 fallback這里是組件 */}<Suspense fallback={<Loading />}><div><MyMain /><Switch><Route path="/mypage1" component={lazy(() => import('./page1.jsx'))} /><Route path="/mypage2" component={lazy(() => import('./page2.jsx'))} /></Switch></div></Suspense></div>)
}// 路由懶加載
ReactDOM.render(<React.StrictMode><BrowserRouter><App /></BrowserRouter></React.StrictMode>,document.getElementById('app')
);