Lazy-Suspense

277 阅读1分钟
/*Lazy与Suspense实现延迟加载
*!!!下面三者缺一不可
 *1 Lazy:封装组件的导入行为import
 *2 Suspense:待加载时要显示的内容
 *3 !!如果文件没请求成功会报错,需要捕获异常 用componentDidCatch
 * 或者用函数 static getDerivedStateFromError(){}
*/

//思考:如何在捕获错误之后重新加载一次呢?

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

//独立请求文件名
const About = lazy(() => import(/*webpackChunkName:"About"*/'./About'));

export default class App extends Component{
    state = {
        hasError:false
    }
    //两捕获函数区别:https://zhuanlan.zhihu.com/p/103487621
    componentDidCatch(){
        this.setState({
            hasError:true
        })
    }
    /*此函数可代替componentDidCatch
    static getDerivedStateFromError(){
        console.log('erro')
        return {
            hasError:true
        }
    }*/
    render(){
        if(this.state.hasError){
            return <div>加载About文件出错</div>
        }
        return(
            <div>
                <Suspense fallback={<div>loading</div>}>
                <About/>
                </Suspense>
            </div>
        )
    }
}

about.jsx

import { Component } from 'react'
import { View, Text } from '@tarojs/components'

export default class Index extends Component { 
  render () {
    return (
      <View className='index'>
        <Text>Hello About!</Text>
      </View>
    )
  }
}