38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import { Component, Suspense, type ReactNode } from 'react';
|
|
import { Alert, Button, Spin } from 'antd';
|
|
import { PageLoadError } from '../lib/loadPage';
|
|
|
|
type Props = { location: string; children: ReactNode };
|
|
export class RouteBoundary extends Component<Props, { location: string; failed: boolean }> {
|
|
state = { location: this.props.location, failed: false };
|
|
static getDerivedStateFromProps(props: Props, state: { location: string }) {
|
|
return props.location !== state.location ? { location: props.location, failed: false } : null;
|
|
}
|
|
static getDerivedStateFromError(error: unknown) {
|
|
if (!(error instanceof PageLoadError)) throw error;
|
|
return { failed: true };
|
|
}
|
|
render() {
|
|
if (this.state.failed)
|
|
return (
|
|
<Alert
|
|
type="error"
|
|
showIcon
|
|
message="页面资源未能加载"
|
|
action={<Button onClick={() => window.location.reload()}>重新加载页面</Button>}
|
|
/>
|
|
);
|
|
return (
|
|
<Suspense
|
|
fallback={
|
|
<div className="page-loading" role="status" aria-label="正在读取页面">
|
|
<Spin size="large" />
|
|
</div>
|
|
}
|
|
>
|
|
{this.props.children}
|
|
</Suspense>
|
|
);
|
|
}
|
|
}
|