Допустим, у меня есть родительский компонент, у него два дочерних элемента, и каждый дочерний элемент заключен в ErrorBoundary
. Если какая-либо ошибка возникает в каком-либо дочернем элементе, ErrorBoundary
будет отображаться вместо дочернего элемента, у которого есть ошибка.
Parent.js
<Parent>
<Child02 />
<Child01 /> {/*It's a Setting icon, check out the pic below*/}
</Parent>
Child02.js
render(){
return(
<ErrorBoundary>
<div>my custom components value </div>
<ErrorComponent />
</ErrorBoundary>
);}
ErrorBoundary.js Вы можете изменить render
то, что вы хотите показать своим пользователям ... и т. Д.
import React from "react";
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
console.log("my custom error: ", error, errorInfo);
// logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
ErrorComponent.js Давайте добавим ошибку внутрь ErrorComponent
export default class ErrorComponent extends Component {
render() {
const x = 5;
x = 7; //it will throw error, because we can't change a constant's value
return <div>hello
{/* some dynamic logic..etc which may cause Error in future */}
</div>;
}
}
Поскольку у компонента ErrorComponent есть ошибки, то Parent компонент будет отображать что-то вроде этого:
<Parent>
<Child01 />
<h1>Something went wrong.</h1> {/*this is what ErrorBoundary renders, it's coming from ErrorBoundary's render method*/}
</Parent>