react 中,我用类组件创建了一个错误边界,在子组件的 componentDidMount 中打印一个未声明的变量。能够捕获到错误,页面上能看见备用 ui 闪了一下,应用还是崩溃了。请问这是为什么?
index.js:
<MyErrorBoundary fallback={<p>Something went wrong!!!</p>}>
<Snapshot />
</MyErrorBoundary>
errorBoundary.js:
import React from 'react';
import myLog from './utils/myLog';
class ErrorBoundary extends React.Component {
constructor(props){
super(props);
this.state = {
hasError: false,
}
}
static getDerivedStateFromError(error){
console.log('getDerivedStateFromError');
return {
hasError: true,
}
}
componentDidCatch(error, info){
myLog('error', error);
myLog('info', info);
// console.error("Caught an error boundary", error, info);
}
render(){
const {children, fallback} = this.props;
const {hasError} = this.state;
myLog('hasError', hasError);
if(hasError){
return fallback;
}
return children;
}
}
export default ErrorBoundary;
snapshot:
componentDidMount(){
// throw new Error('componentDidMount 出错了!');
console.log(undefinedVariety);
}
后来我尝试用 react-error-boundary,结果是一样的。
模块版本:
"react": "^16.13.1",
"@types/react": "^16.9.41",
"react-error-boundary": "^5.0.0",