feat: ErrorBoundary增加重试功能

pull/56/head
moonrailgun 2 years ago
parent b4c8f0967f
commit 7b7f4ed58e

@ -1,3 +1,4 @@
import { Button } from 'antd';
import React, { PropsWithChildren } from 'react'; import React, { PropsWithChildren } from 'react';
import { t } from 'tailchat-shared'; import { t } from 'tailchat-shared';
import { Problem } from './Problem'; import { Problem } from './Problem';
@ -7,6 +8,13 @@ interface ErrorBoundaryProps {
description?: string; description?: string;
} }
const defaultState = {
error: undefined,
info: {
componentStack: '',
},
};
export class ErrorBoundary extends React.Component< export class ErrorBoundary extends React.Component<
PropsWithChildren<ErrorBoundaryProps>, PropsWithChildren<ErrorBoundaryProps>,
{ {
@ -16,17 +24,16 @@ export class ErrorBoundary extends React.Component<
}; };
} }
> { > {
state = { state = defaultState;
error: undefined,
info: {
componentStack: '',
},
};
componentDidCatch(error: Error | null, info: any) { componentDidCatch(error: Error | null, info: any) {
this.setState({ error, info }); this.setState({ error, info });
} }
reset = () => {
this.setState(defaultState);
};
render() { render() {
const { message, description, children } = this.props; const { message, description, children } = this.props;
const { error, info } = this.state; const { error, info } = this.state;
@ -36,6 +43,7 @@ export class ErrorBoundary extends React.Component<
typeof message === 'undefined' ? (error || '').toString() : message; typeof message === 'undefined' ? (error || '').toString() : message;
const errorDescription = const errorDescription =
typeof description === 'undefined' ? componentStack : description; typeof description === 'undefined' ? componentStack : description;
if (error) { if (error) {
return ( return (
<Problem <Problem
@ -43,6 +51,9 @@ export class ErrorBoundary extends React.Component<
<> <>
<h3>{t('页面出现了一些问题')}</h3> <h3>{t('页面出现了一些问题')}</h3>
<p title={errorDescription ?? ''}>{errorMessage}</p> <p title={errorDescription ?? ''}>{errorMessage}</p>
<Button size="small" onClick={this.reset}>
{t('重试')}
</Button>
</> </>
} }
/> />

Loading…
Cancel
Save