React 之 Suspense和lazy

一. Suspense

参考链接:https://react.docschina.org/reference/react/Suspense

suspense:n. 焦虑、悬念

<Suspense> 允许你显示一个退路方案(fallback)直到它的所有子组件完成加载。

<Suspense fallback={
    
    <Loading />}>
  <SomeComponent />
</Suspense>

二. lazy

lazy的实现类似于如下asyncComponent的实现代码:

function asyncComponent(importComponent) {
    
    
	class AsyncComonent extends React.Component {
    
    
		constructor(props) {
    
    
			super(props);
			this.state = {
    
    
				com: null
			}
		}
		async componentDidMount() {
    
    
			const {
    
     default: com } = await importComponent();
			this.setState({
    
    
				com
			});
		}
		render() {
    
    
			const C = this.state.com;
			return C ? <C ...{
    
    this.props} /> : null;
		}
	}

}
const routers = {
    
    
	demo: {
    
    
		path: '/homepage',
		renderComponent: asyncComponent(() => import('../homepage/main.jsx'))
	}
}

:使用import()动态导入后返回一个promise,但是通过lazy包裹后可以得到一个直接渲染的组件。
在这里插入图片描述

参考链接

猜你喜欢

转载自blog.csdn.net/yexudengzhidao/article/details/132245120
今日推荐