也不怕大家笑话,看到react.lazy()我第一个想到的居然是vue 中的一个vue-lazy 用户懒加载的插件。但是这两个差别还是有点大的。
好了我们言归正传,开始来看看我们的react.lazy()
其实看见lazy()大家见名知意,就知道是来做懒加载的,但是这个是来做组件的懒加载。
为什么需要react.lazy()
我们所知道的是,webpack 打包时我们如果没有分模块打包的话,就会把所以的文件都打入一个包中,这样的话加载就会很慢,我们怎末解决这个问题呢,在vue 中我们主要用的方式时动态导入懒加载的方式
这个我就不在这里写了
链接: link.
感兴趣的大家可以去阅读上方的地址
现在我们来看看react.lazy()是怎么做的
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
// Displays <Spinner> until OtherComponent loads
<React.Suspense fallback={<Spinner />}>
<div>
<OtherComponent />
</div>
</React.Suspense>
);
}
我们需要注意的这个组件他会返回一个propmise,需要使用函数来调用,而且还是主动抛错的,resolve
但是有一个问题是当我们在懒加载时组件组件在没有加载时,页面该怎样呈现呢?
这个我么就要引入Suspense了,这个就是来解决这个问题的
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const TowComponent = React.lazy(() => import('./TowComponent'))
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
<TowComponent />
</Suspense>
);
}
如果组件在懒加载的时候出错了怎么办呢?
我们可以通过异常捕获边界来解决这个问题
import MyErrorBoundary from './MyErrorBoundary';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const TowComponent = React.lazy(() => import('./TowComponent'))
function MyComponent() {
return (
<MyErrorBoundary>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
<TowComponent />
</Suspense>
<MyErrorBoundary>
);
}
class MyErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能够显示降级后的 UI
return { hasError: true };
}
componentDidCatch(error, info) {
// 你同样可以将错误日志上报给服务器
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// 你可以自定义降级后的 UI 并渲染
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default MyErrorBoundary ;
注意点
react.lazy()只支持默认导入,不支持重命名的方式
const Tow = React.lazy(() => import('./TowComponent'))
如果你非要重名等操作,你可以创建一个中间模块进行
// 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"));