87 lines
2.7 KiB
TypeScript
87 lines
2.7 KiB
TypeScript
import React from 'react';
|
||
import { useNavigate, useRouteError } from 'react-router-dom';
|
||
import { AlertCircle, Home, RefreshCw } from 'lucide-react';
|
||
|
||
/**
|
||
* 路由错误降级组件
|
||
*
|
||
* 用于 React Router 的 errorElement
|
||
* 当路由加载或渲染出错时显示
|
||
*/
|
||
const ErrorFallback: React.FC = () => {
|
||
const navigate = useNavigate();
|
||
const error = useRouteError() as Error;
|
||
|
||
const handleGoHome = () => {
|
||
navigate('/', { replace: true });
|
||
};
|
||
|
||
const handleReload = () => {
|
||
window.location.reload();
|
||
};
|
||
|
||
return (
|
||
<div className="flex h-screen w-screen flex-col items-center justify-center bg-slate-50 p-8">
|
||
<div className="max-w-md text-center">
|
||
{/* 错误图标 */}
|
||
<div className="mb-6 flex justify-center">
|
||
<div className="rounded-full bg-red-100 p-6">
|
||
<AlertCircle className="h-16 w-16 text-red-500" />
|
||
</div>
|
||
</div>
|
||
|
||
{/* 错误标题 */}
|
||
<h1 className="mb-3 text-3xl font-bold text-slate-800">
|
||
页面加载失败
|
||
</h1>
|
||
|
||
{/* 错误描述 */}
|
||
<p className="mb-8 text-slate-600">
|
||
抱歉,页面在加载过程中出现了问题。请尝试刷新页面或返回首页。
|
||
</p>
|
||
|
||
{/* 开发环境显示错误详情 */}
|
||
{import.meta.env.DEV && error && (
|
||
<div className="mb-6 rounded-lg bg-red-50 p-4 text-left">
|
||
<p className="mb-2 text-sm font-semibold text-red-800">错误信息:</p>
|
||
<pre className="overflow-auto text-xs text-red-700">
|
||
{error.message || error.toString()}
|
||
</pre>
|
||
{error.stack && (
|
||
<details className="mt-2">
|
||
<summary className="cursor-pointer text-sm font-semibold text-red-800">
|
||
堆栈跟踪
|
||
</summary>
|
||
<pre className="mt-2 overflow-auto text-xs text-red-600">
|
||
{error.stack}
|
||
</pre>
|
||
</details>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{/* 操作按钮 */}
|
||
<div className="flex justify-center gap-4">
|
||
<button
|
||
onClick={handleGoHome}
|
||
className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 text-white transition-colors hover:bg-blue-700"
|
||
>
|
||
<Home className="h-5 w-5" />
|
||
返回首页
|
||
</button>
|
||
<button
|
||
onClick={handleReload}
|
||
className="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-6 py-3 text-slate-700 transition-colors hover:bg-slate-50"
|
||
>
|
||
<RefreshCw className="h-5 w-5" />
|
||
刷新页面
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default ErrorFallback;
|
||
|