57 lines
1.4 KiB
JavaScript
57 lines
1.4 KiB
JavaScript
import React from 'react';
|
||
import { Icon } from './icons';
|
||
|
||
class ErrorBoundary extends React.Component {
|
||
constructor(props) {
|
||
super(props);
|
||
this.state = { hasError: false, error: null };
|
||
}
|
||
|
||
static getDerivedStateFromError(error) {
|
||
return { hasError: true, error };
|
||
}
|
||
|
||
componentDidCatch(error, errorInfo) {
|
||
console.error('ErrorBoundary caught error:', error, errorInfo);
|
||
}
|
||
|
||
handleReload = () => {
|
||
window.location.reload();
|
||
};
|
||
|
||
handleGoHome = () => {
|
||
window.location.href = '/';
|
||
};
|
||
|
||
render() {
|
||
if (this.state.hasError) {
|
||
return (
|
||
<div className="error-boundary">
|
||
<div className="error-boundary__content">
|
||
<Icon name="info" size={48} />
|
||
<h2>出错了</h2>
|
||
<p>抱歉,应用遇到了问题。</p>
|
||
{process.env.NODE_ENV === 'development' && (
|
||
<pre className="error-boundary__details">
|
||
{this.state.error?.toString()}
|
||
</pre>
|
||
)}
|
||
<div className="error-boundary__actions">
|
||
<button onClick={this.handleGoHome} className="btn btn-secondary">
|
||
返回首页
|
||
</button>
|
||
<button onClick={this.handleReload} className="btn btn-primary">
|
||
重新加载
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return this.props.children;
|
||
}
|
||
}
|
||
|
||
export default ErrorBoundary;
|