react16
以后,官方为class类组件
添加了componentDidCatch
获取异常信息的生命周期。
然而,react hook
这类函数式组件却还没有。
那么,如何为react hook
函数式组件捕获异常信息实现埋点呢?
方法一
自己手动实现try catch
,但是官方不推荐如此
方法二
引入第三方边界捕获插件容器,例如react-error-boundary
npm install --save react-error-boundary
https://www.npmjs.com/package/use-error-boundary#breaking-changes-in-2x
方法三(博主推荐做法)
为最上层容器组件(例如antdpro的BasicLayout
)的return dom的props.children包裹一层ErrorBoundaryContainer
类class
容器组件(该组件由我们自行实现)
import React, { Component } from 'react';
import cookie from 'react-cookies';
class ErrorBoundaryContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
// hasError: false,
};
}
componentDidCatch(error, info) {
console.warn('componentDidCatch error, info====>', '----' + error + '----', info);
// this.setState({ hasError: true });
// TODO:底下这行代码上报埋点信息 根据自己的情况来改
window.mmjWebtrack && window.mmjWebtrack.updateTrackError && window.mmjWebtrack.updateTrackError({ message: error, info });
}
render() {
// if (this.state.hasError) return <p>halo,出现了未知的错误!</p >
return (
<React.Fragment>
{this.props.children}
</React.Fragment>
);
}
}
export default ErrorBoundaryContainer;