背景: React版本:16.13.1 浏览器:Chrome版本-81.0.4044.122
尽管下面的代码段中使用了ErrorBoundary,但它在浏览器中引发了错误。 处理的错误显示几毫秒,然后在浏览器中显示实际的错误。 有人可以帮我这个忙吗。
下面是整个代码段:
class CustomErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
class BuggyComponent extends Component {
constructor(props) {
super(props);
this.state = { Clicked: "false" };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
Clicked: "true"
});
}
render() {
if (this.state.Clicked === "true") {
// Simulate a JS error
throw new Error('I crashed!');
}
return <button onClick={this.handleClick}>{this.props.Label}</button>;
}
}
function App() {
return (
<div>
<CustomErrorBoundary>
<BuggyComponent Label="I catch exceptions"/>
</CustomErrorBoundary>
</div>
);
}
export default App;
答案 0 :(得分:1)