我有一个组件
import React, {Component} from 'react';
class Buggy extends Component {
state = {greeting : 'Welcome'};
componentDidMount() {
throw new Error('An error has occured');
}
render() {
return (
<h2>{this.state.greeting}</h2>
);
}
}
export default Buggy;
还有一个典型的ErrorBoundary
类
import React, {Component} from 'react';
class ErrorBoundary extends Component {
state = {error: null, errorInfo: null};
componentDidCatch(error, errorInfo) {
this.setState({
error: error,
errorInfo: errorInfo
})
}
render() {
if(this.state.errorInfo) {
return (
<div>
<h2>Oops! Something went wrong.</h2>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
在App.js
<ErrorBoundary>
<Buggy />
</ErrorBoundary>
</Fragment>
尚未处理错误。
我在做什么错了?
答案 0 :(得分:-1)
componentDidCatch()用于记录错误信息,而不是呈现后备UI,为此目的,请使用getDerivedStateFromError()。
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}