码桶
发现社区成员的开源项目
ErrorBoundary.tsx1.1 KB
import { Component, type ReactNode } from 'react'
interface Props { children: ReactNode }
interface State { error: Error | null }
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null }
static getDerivedStateFromError(error: Error): State {
return { error }
}
componentDidCatch(error: Error, info: unknown) {
console.error('[ErrorBoundary]', error, info)
}
render() {
if (this.state.error) {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-4 p-6 text-center">
<h1 className="text-lg font-semibold text-red-600">页面渲染出错</h1>
<pre className="max-w-xl overflow-auto rounded-lg bg-muted p-4 text-left text-xs text-muted-foreground">
{this.state.error.message}
</pre>
<button
onClick={() => location.reload()}
className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
>
刷新重试
</button>
</div>
)
}
return this.props.children
}
}