react-loadable 實現路由懶加載


安裝依賴:

yarn add react-loadable

創建通用工具類:

src/util/loadable.js

/*路由懶加載(異步組件)*/
import React from 'react';
import Loadable from 'react-loadable';

//通用的過場組件
const LoadingComponent =()=>{
    return (
        <div>loading</div>
    ) 
}

//過場組件默認采用通用的,若傳入了loading,則采用傳入的過場組件
export default (loader,loading = LoadingComponent)=>{
    return Loadable({
        loader,
        loading
    });
}

router里面調用方式改為如下

/*配置路由*/
import React, { Fragment } from 'react'
import { BrowserRouter, Route } from 'react-router-dom'
import loadable from '../util/loadable'

const Home = loadable(()=>import('@pages/home'))

const Routes = () => (
    <BrowserRouter>
        <Route path="/home" component={Home}/>
    </BrowserRouter>
);

export default Routes

封裝之后,laodable只需寫一次,改變的只是組件的引入方式,這樣一來就方便多了,

react-loadable是以組件級別來分割代碼的,這意味着,我們不僅可以根據路由按需加載,還可以根據組件按需加載,使用方式和路由分割一樣,只用修改組件的引入方式即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM