daily-share
daily-share copied to clipboard
React中componentDidCatch处理错误异常捕获、配合装饰器模式优雅处理(2021-04-24)
错误异常捕获组件
/*
* @Author: yaogeng.zhu
* @Date: 2021-04-24 12:37:42
* @Last Modified by: yaogeng.zhu
* @Last Modified time: 2021-04-24 13:14:58
*/
import React from 'react';
import PropTypes from 'prop-types';
class ErrorBoundary extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
};
constructor(props) {
super(props);
this.state = {
// errorInfo: null,
hasError: false,
};
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch() {
// this.setState({
// errorInfo,
// });
}
render() {
const { hasError } = this.state;
if (hasError) {
return <h1>错误组件地址</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
简单用法
<ErrorBoundary>
<Demo />
</ErrorBoundary>
采用装饰器模式处理
import catchreacterror from 'catch-react-error'; // 这里采用了第三方库方式去处理
import ErrorBoundary from '.' // 自己写的错误异常组件
@catchreacterror(ErrorBoundary)
class App extends React.component { ... }