What are Error Boundaries in ReactJS?
What are Error Boundaries in ReactJS?
Error boundaries in ReactJS are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. They act as a catch mechanism for unhandled errors in the component tree, allowing an application to continue running and providing a better user experience in the event of an error.
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. However, they do not catch errors for:
To define an error boundary, you create a class component that implements either or both of the lifecycle methods static getDerivedStateFromError()
or componentDidCatch()
. The getDerivedStateFromError()
method is used to render a fallback UI after an error has been thrown, while componentDidCatch()
is used to log error information.
Here's an example of an error boundary component:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào