先放上程序,新建一个components。
import React, { Component,lazy,Suspense } from 'react';
export default class Index extends Component {
constructor(props) {
super(props);
this.state = {
};
}
_renderLazy = ()=>{
let Lazy;
const {component,delay,...other} = this.props;
if(!component || component.constructor.name !=='Promise'){
Lazy = import('./error');
}
Lazy = lazy(()=>{
return new Promise(resolve =>{
setTimeout(()=>{
resolve(component);
},delay||200)
})
})
return <Lazy {...other}/>
}
render() {
return (
<div>
<Suspense fallback={<div>加载中...</div>}>
{this._renderLazy()}
</Suspense>
</div>
)
}
}
使用方法:
说明
1.源码中,LazyOut传入一个组件,这个可以达到按需引入的目的,默认延迟200ms加载
2.必须传入一个Promise对象,如果组件有错误,会引入并渲染.error的内容。
3.建议将需要懒加载的组件,写成变量的形式,可以懒加载图片,列表,echats等。
4.使用react中的Suspense 和 Lazy