๐ย Reference
๐ย Chapter
componentDidCatch(error, info)
getDerivedStateFromError(error)
import React from "react";
class ErrorBoundary extends React.Component<
{ fallback: React.ReactNode },
{ hasError: boolean }
> {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: Error) {
// ์๋ฌ ๊ฐ์ง ์ state ๋ณ๊ฒฝ โ fallback ๋ ๋๋ง
return { hasError: true };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error("Error caught by boundary:", error, info);
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
import React from "react";
import ErrorBoundary from "./ErrorBoundary";
import BrokenComponent from "./BrokenComponent";
export default function App() {
return (
<ErrorBoundary fallback={<h2>๋ฌธ์ ๊ฐ ๋ฐ์ํ์ต๋๋ค ๐ฅ</h2>}>
<BrokenComponent />
</ErrorBoundary>
);
}