我正在学习React,并且当前的主题是“懒加载”。
我在想为什么懒加载不是React的默认设置,并由React处理,而不需要开发人员编写重复的代码?
例如:
在课程中,我们希望懒惰地加载“Posts”组件,因为在该组件中,只有在特定路线上时才进行渲染。因此,他替换了原本的代码:
import Posts from './containers/posts'
使用
const Posts = React.lazy(() => import('./containers/posts'))
他在使用时替换掉了原内容
<Route path='/posts' component={Posts}>
使用
<Route
path='/posts'
render={() => (
<Suspense>
<Posts>
</Suspense)}
>
基本上只需在某个React组件中包装我们想要lazyload的组件即可。