react的lazy和Suspense的使用

懒加载

import React, {
    
     Component, lazy, Suspense } from 'react';

const Child = lazy(() => import("./Child"))   // 导出lazy和suspense 使用lazy导出子组件

class App extends Component {
    
    
  state = {
    
    
    show: false
  }

  handleClick = () => {
    
    
    this.setState({
    
    
      show: true
    })
  }
// 使用Suspense包裹
  render() {
    
    
    return (
      <div>
        <div>
          <button onClick={
    
    this.handleClick}>show</button>
        </div>
        <Suspense fallback={
    
    <div>loading...</div>}>  
          {
    
    
            this.state.show && <Child></Child>
          }
        </Suspense>
      
      </div>
    );
  }
}

export default App;

import React from 'react'

export default function Child() {
    
    
  return (
    <div>
      child
    </div>
  )
}

猜你喜欢

转载自blog.csdn.net/shadowfall/article/details/114670059
今日推荐