์ ๊ฑฐํ ๋
* componentWillUnmount (์ปดํผ๋ํธ๊ฐ ์ฌ๋ผ์ง๊ธฐ ์ง์ ์ ํธ์ถ, ๋ฑ๋ก๋ ์ปดํผ๋ํธ ์ ๊ฑฐ)
์๋ฌ ๋ฐ์ ์ฐพ๊ธฐ
์๋ฌ๊ฐ ๋ฐ์ํ๊ฒ ๋๋ฉด ๋ธ๋ผ์ฐ์ ์์์๋ ํฐ ๋ฐํํ๋ฉด์ ๋๋ค. ๊ทธ๋ฌ๋ฏ๋ก ์ง๊ด์ ์ผ๋ก ๋ณด์ฌ์ฃผ๊ฒ ํ๋ ค๊ณ ํฉ๋๋ค.
import React from "react";
import User from "./User";
import ErrorBoundary from "./ErrorBoundary";
import ReactDOM from "react-dom";
function App() {
const user = {
id: 1,
username: "suyang"
};
return (
<ErrorBoundary>
<User />
</ErrorBoundary>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React from "react";
function User({ user }) {
return (
<div>
<div>
<b>ID</b>: {user.id}
</div>
<div>
<b>Username</b>: {user.username}
</div>
</div>
);
}
export default User;
import React, { Component } from "react";
class ErrorBoundary extends Component {
state = {
error: false
};
componentDidCatch(error, info) {
console.log("err");
console.log({
error,
info
});
this.setState({
error: true
});
}
render() {
if (this.state.error) {
return <h1>์๋ฌ๋ฐ์</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;