class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
// Define a state variable to track whether is an error or not
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 use your own error logging service here
console.log({ error, errorInfo });
}
render() {
// Check if the error is thrown
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<div>
<h2>There was an error</h2>
<button
type="button"
onClick={() => this.setState({ hasError: false })}
>
Try again?
</button>
</div>
);
}
// Return children components in case of no error
return this.props.children;
}
}
export default ErrorBoundary;
1条答案
按热度按时间l0oc07j21#
我猜你的
error.js
没有捕捉和正确处理你的404错误。您的GlobalError
组件只是记录useEffect()
的错误。我想您最好采用
ErrorBoundary
组件来成功地显示错误消息(在您的示例中,出现了错误!)