亲宝软件园·资讯

展开

React代码分割的实现方法介绍

码农小菲 人气:0

代码分割

React.lazy&Suspense

//使用前:
import OtherComponent from './OtherComponent';
//使用之后:
const OtherComponent = React.lazy(() => import('./OtherComponent'))
   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>
     );
   }

异常捕获边界(Error boundaries)

如果模块加载失败(如网络问题),它会触发一个错误。可以通过异常捕获边界(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)

// 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"));

加载全部内容

相关教程
猜你喜欢
用户评论