您的位置:首页 > Web前端 > React

React 代码分割 & loading 页面的实现

2020-07-14 06:13 841 查看

React.lazy 和 Suspense

const Component = React.lazy(() => import('./Component));

React.lazy函数可以实现动态引入组件,它会在组件首次渲染时,自动导入Component。

渲染lazy组件需要借助Suspense组件,它有一个fallback属性,可以传入在加载过程中想要展示的元素。

Suspence可以放置在懒加载组件之上的任何位置。

在路由进行代码分割

原先页面加载时,默认会把路由上的所有组件一起加载过来(比如Home、Detail、Login等页面),虽然这样能够让
页面切换时间变短,但会严重影响首屏的加载时间,因此有必要对路由中的组件进行代码分割,实现懒加载:

import React, { Suspense, lazy } from 'react';
//懒加载
const Header = lazy(()=>import('./common/header'));
const Detail = lazy(()=>import('./pages/detail'));
const Login = lazy(()=>import('./pages/login'));
const Register = lazy(()=>import('./pages/register'));
const Footer = lazy(()=>import('./common/footer'));
<BrowserRouter>
<Suspense fallback={<div>loading...</div>}>
<Route path={["/detail/:id", "/"]} exact component={Header}/>
<Route path='/' exact component={Home}/>
<Route path='/detail/:id' component={Detail}/>
<Route path='/login' component={Login}/>
<Route path='/register' component={Register}/>
<Route path={["/detail/:id", "/"]} exact component={Footer}/>
</Suspense>
</BrowserRouter>

如此编写后,我们发现页面在加载和切换时会加载fallback中的loading,切换所需时间明显延长,但用户是可以接受的。

loading 美化

<Suspense fallback={<Loading><Spin size="large" /></Loading>}>

其中Spin是AntD引入的组件,Loading则封装了容器的样式(Styled-Component):

export const Loading = styled.div`
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
`;

这样我们就可以实现一个在屏幕中央的loading效果。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: