lazy&Suspense 基本使用
JS 模塊延時(shí)加載,做代碼拆分
import React, { Component, lazy, Suspense } from 'react'
// 這里使用 webpackChunkName 可以自定義 chunk 的名稱方便調(diào)試
const Detail = lazy(() => import(/* webpackChunkName: "LoadingDetail" */'./Detail'))
class App extends Component {
render () {
return (
<div>
<Suspense fallback={<div>Loading</div>}>
<Detail></Detail>
</Suspense>
</div>
)
}
}
export default App
使用 React生命周期 攔截組件加載失敗
import React, { Component, lazy, Suspense } from 'react'
// 這里使用 webpackChunkName 可以自定義 chunk 的名稱方便調(diào)試
const Detail = lazy(() => import(/* webpackChunkName: "LoadingDetail" */'./Detail'))
class App extends Component {
state = {
hasError: false
}
// 組件加載出錯(cuò)會(huì)調(diào)用的生命周期
componentDidCatch () {
this.setState({
hasError: true
})
}
render () {
if (this.state.hasError) {
return <div>加載出錯(cuò)</div>
}
return (
<div>
<Suspense fallback={<div>Loading</div>}>
<Detail></Detail>
</Suspense>
</div>
)
}
}
export default App
使用 getDerivedStateFromError() 攔截組件加載失敗
import React, { Component, lazy, Suspense } from 'react'
// 這里使用 webpackChunkName 可以自定義 chunk 的名稱方便調(diào)試
const Detail = lazy(() => import(/* webpackChunkName: "LoadingDetail" */'./Detail'))
class App extends Component {
state = {
hasError: false
}
// 一旦出現(xiàn)錯(cuò)誤,就會(huì)返回一個(gè)新的 state 數(shù)據(jù)并且合并到現(xiàn)有的 state 中
static getDerivedStateFromError () {
return {
hasError: true
}
}
render () {
if (this.state.hasError) {
return <div>加載出錯(cuò)</div>
}
return (
<div>
<Suspense fallback={<div>Loading</div>}>
<Detail></Detail>
</Suspense>
</div>
)
}
}
export default App