React 使用 lazy
lay 懒加载,也可以是异步加载
使用必须用 lazy,Suspense 做到懒加载
import React, { Component, Fragment, lazy, Suspense } from 'react'
const SecondComponent = lazy(() => {
  return import('./Second.js')
})
- 使用 懒加载的时候 必须用 Suspense 用了 Suspense 里面必须用 fallback 它的作用就是当懒加载没有加载出来的时候,它显示的内容
import React, { Component, Fragment, lazy, Suspense } from 'react'
const SecondComponent = lazy(() => {
  return import('./Second.js')
})
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      message: '首页',
      hasError: false,
    }
  }
  
  componentDidCatch() {
    this.setState({
      hasError: true,
    })
  }
  render() {
    if (this.state.hasError) {
      return <div>渲染失败</div>
    } else {
      return (
        <Fragment>
          <div>{this.state.message}</div>
          <Suspense fallback={<div>loading</div>}>
            <SecondComponent></SecondComponent>
          </Suspense>
        </Fragment>
      )
    }
  }
}
export default App