有时候某个js加载失败会导致页面报错,不能正常展示 例如Something went wrong
如图

错误示例
写一个错误捕获的组件
注意:这个组件只有在打包后才生效,本地运行是不能捕获到错误的
import { RedoOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import React, { Component } from 'react';
import './error.less';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// 你可以在这里处理错误信息,例如发送到服务器记录
console.error('ErrorBoundary caught an error', error, info);
this.setState({ hasError: true });
}
refresh() {
window.location.reload();
}
render() {
if (this.state.hasError) {
// 可以在这里渲染一个错误提示
return (
<>
<div className="error-container">
<h1 className="error-title">页面出现错误</h1>
<p className="error-message">
很抱歉,资源加载失败,导致页面无法正常显示。
</p>
<div className="error-details">
<p>描述: 资源加载失败</p>
<p>
建议:
请检查网络状态并刷新重试,如果问题依旧,请联系我们的技术支持。
</p>
<p style={{ textAlign: 'center' }}>
<Button
type="primary"
className="mr-20"
icon={<RedoOutlined />}
onClick={this.refresh}
>
刷新重试
</Button>
</p>
</div>
</div>
</>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
error.less文件
.error-container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 10%);
margin-top: 216px;
p {
padding: 10px;
}
}
.error-title {
color: #d9534f;
font-size: 24px;
margin-bottom: 10px;
}
.error-message {
color: #333;
font-size: 18px;
margin-bottom: 20px;
}
.error-details {
color: #777;
font-size: 14px;
}
在全局组件外面用错误组件包裹住页面

示例

效果