定义错误展示形式
import React, { Component } from 'react'
export default class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能够显示降级后的 UI
console.log('error')
return { hasError: true };
}
render() {
if (this.state.hasError) {
// 你可以自定义降级后的 UI 并渲染
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
设置错误边界
import React, { lazy, Suspense, useState, startTransition } from 'react'
import ErrorBoundary from './07_ErrorBoundary'
const Welcome = lazy(() => import('../components/Wellcome'))
const Welcome2 = lazy(() => import('../components/Wellcome2'))
export default function App() {
const [show, setShow] = useState(true)
const handleClick = () => {
startTransition(() => {
// 延后执行
setShow(!show)
})
}
return (
<div>
{/* 组件没有加载前就会显示loading */}
<button onClick={handleClick}>点击</button>
{/* 处理错误边界 */}
<ErrorBoundary>
<Suspense fallback={<div>loading</div>}>
{show ? <Welcome /> : <Welcome2 />}
</Suspense>
</ErrorBoundary>
</div>
)
}