我一直在尝试在React中实现 ErrorBoundary 。 我只是在App.js中创建了一个称为counter组件的计数器。 如果计数器的值小于0,则会引发错误。 作为后备UI,我制作了错误边界组件来处理错误(如果存在)。
当我将计数器的值从0减小时,我的errorBoundary组件似乎可以工作一秒钟。一秒钟,它显示了用于错误处理目的的预期后备UI。但是就在那之后,整个react应用都崩溃了。
我正在附上屏幕截图: crashed app screenshot fallbackUI screenshot
ErrorBoundary.js
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error) {
console.log("here getDerivedStateFromError");
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log("here did catch");
// You can also log the error to an error reporting service
// logErrorToMyService(error, errorInfo);
this.setState({
error: error,
errorInfo: errorInfo,
hasError: true
});
}
render() {
console.log("Inside Error Boundary render Function");
return this.state.error ? (
<h1> Something Went Wrong ... Error Boundary Caught it!</h1>
) : (
<>
{this.props.children}
</>
);
}
}
export default ErrorBoundary;
Counter.js
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
}
addValue = () => {
this.setState({
value: this.state.value + 1
});
};
subValue = () => {
this.setState({
value: this.state.value - 1
});
};
render() {
if (this.state.value < 0) {
throw new Error("Simulating React App Crash!");
} else {
return (
<>
<p>{this.state.value}</p>
<button onClick={this.addValue}>+</button>
<button onClick={this.subValue}>-</button>
</>
);
}
}
}
export default Counter;
App.js
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import Counter from "./components/Counter";
import ErrorBoundary from "./components/ErrorBoundary";
function App() {
return (
<div className="App">
<div>
<ErrorBoundary>
<Counter />
<p>Here if the value counter value goes below 0, it throws error.</p>
</ErrorBoundary>
</div>
<hr></hr>
<div>
<ErrorBoundary>
<Counter />
<p>Here if the value counter value goes below 0, it throws error.</p>
</ErrorBoundary>
</div>
<hr></hr>
<div>
<ErrorBoundary>
{" "}
<Counter />
<Counter />
</ErrorBoundary>
<p>Here anyone of the two counter value goes below 0, both of them throws error together.</p>
</div>
<hr></hr>
<div>
<Counter />
<p>Without any Error Boundary. It will crash whole App if counter is less than 0</p>
</div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
Learn React
</a>
</header>
</div>
);
}
export default App;