UNPKG

2.31 kBJavaScriptView Raw
1import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
2import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
3import _inherits from 'babel-runtime/helpers/inherits';
4
5var _class, _temp;
6
7import React from 'react';
8import PropTypes from 'prop-types';
9
10DefaultUI.propTypes = {
11 error: PropTypes.object,
12 errorInfo: PropTypes.object
13};
14
15function DefaultUI() {
16 return '';
17}
18
19var ErrorBoundary = (_temp = _class = function (_React$Component) {
20 _inherits(ErrorBoundary, _React$Component);
21
22 function ErrorBoundary(props) {
23 _classCallCheck(this, ErrorBoundary);
24
25 var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
26
27 _this.state = { error: null, errorInfo: null };
28 return _this;
29 }
30
31 ErrorBoundary.prototype.componentDidCatch = function componentDidCatch(error, errorInfo) {
32 this.setState({
33 error: error,
34 errorInfo: errorInfo
35 });
36
37 var afterCatch = this.props.afterCatch;
38
39
40 if ('afterCatch' in this.props && typeof afterCatch === 'function') {
41 this.props.afterCatch(error, errorInfo);
42 }
43 };
44
45 ErrorBoundary.prototype.render = function render() {
46 var _props$fallbackUI = this.props.fallbackUI,
47 FallbackUI = _props$fallbackUI === undefined ? DefaultUI : _props$fallbackUI;
48
49
50 if (this.state.errorInfo) {
51 return React.createElement(FallbackUI, {
52 error: this.state.error,
53 errorInfo: this.state.errorInfo
54 });
55 }
56 // Normally, just render children
57 return this.props.children;
58 };
59
60 return ErrorBoundary;
61}(React.Component), _class.propTypes = {
62 children: PropTypes.element,
63 /**
64 * 捕获错误后的自定义处理, 比如埋点上传
65 * @param {Object} error 错误
66 * @param {Object} errorInfo 错误详细信息
67 */
68 afterCatch: PropTypes.func,
69 /**
70 * 捕获错误后的展现 自定义组件
71 * @param {Object} error 错误
72 * @param {Object} errorInfo 错误详细信息
73 * @returns {Element} 捕获错误后的处理
74 */
75 fallbackUI: PropTypes.func
76}, _temp);
77ErrorBoundary.displayName = 'ErrorBoundary';
78export { ErrorBoundary as default };
\No newline at end of file