日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React代碼分割的實現方法介紹_React

作者:碼農小菲 ? 更新時間: 2022-12-30 編程語言

代碼分割

  • 打包是個很棒的技術,但隨著代碼量的增加,容易出現體積過大而導致加載時間過長。為避免這種情況的出現,在前期就思考該問題并對代碼包進行分割是個不錯的選擇。
  • 對應用進行代碼分割能夠幫助你“懶加載”當前用戶所需要的內容,提高應用性能。盡管并沒有減少應用整體的代碼體積,但可以避免加載用戶不需要的代碼,并在初始加載的時候減少所需加載的代碼量。
  • 簡單理解:是性能優化的一種解決方案。比如我們的路由系統中有100個組件,我們在react項目啟動時不需要對這100個組件都進行編譯,只編譯當前URL對應的組件,這就可以用到代碼分割的功能;

React.lazy&Suspense

  • 動態引入
//使用前:
import OtherComponent from './OtherComponent';
//使用之后:
const OtherComponent = React.lazy(() => import('./OtherComponent'))
  • 在組件首次渲染時,自動導入包含該組件的包
  • React.lazy 接受一個函數,這個函數需要動態調用import()。它必須返回一個Promist,該Promise 需要resolve 一個default export 的react組件
  • 然后應在 Suspense 組件中渲染 lazy 組件,這樣可以在等待加載 lazy 組件時做優雅降級(如 loading 指示器等)
   import React, { Suspense } from 'react';
   const  OtherComponent = React.lazy(() => import('./OtherComponent'))
   const AnotherComponent = React.lazy(() => import('./AnotherComponent'))
   function MyComponent() {
     return (
       <div>
        <Suspense fallback={<div>Loading...</div>}>
           <section>
             <OtherComponent />
             <AnotherComponent />
           </section>
         </Suspense>
       </div>
     );
   }
  • fallback:接受任何在組件加載過程中你想展示的 React 元素
  • Suspense 組件置于懶加載組件之上的任何位置

異常捕獲邊界(Error boundaries)

如果模塊加載失?。ㄈ缇W絡問題),它會觸發一個錯誤??梢酝ㄟ^異常捕獲邊界(Error boundaries)技術來處理這些情況,以顯示良好的用戶體驗并管理恢復事宜。

import React, { Suspense } from 'react';
import MyErrorBoundary from './MyErrorBoundary';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
const MyComponent = () => (
 <div>
   <MyErrorBoundary>
     <Suspense fallback={<div>Loading...</div>}>
       <section>
         <OtherComponent />
         <AnotherComponent />
       </section>
     </Suspense>
   </MyErrorBoundary>
 </div>
);

基于路由的代碼分割

可以選擇從路由開始實現代碼分割。

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

命名導出(Named Exports)

  • React.lazy 目前只支持默認導出(default exports)
  • 若導出其他模塊,可以創建一個中間模塊,來重新導出為默認模塊
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));

原文鏈接:https://blog.csdn.net/xbczrz/article/details/127925688

欄目分類
最近更新