class LifeCycleMethod extends Component {
// 3.1 DOM에서 언 마운트 되어 제거되기 직전에 실행
componentWillUnmount() {
console.log('DOM에서 언 마운트 되어 제거되기 직전에 실행 됨')
}
}
오류 처리
컴포넌트 렌더링, 라이프 사이클 훅이 실행될 때 오류가 발생한 경우 호출됩니다.
라이프 사이클 훅
설명
자손 컴포넌트 오류 발생 시 호출
자손 컴포넌트 오류 발생 시 호출
getDerivedStateFromError 메서드는 자식 컴포넌트에서 오류가 발생되면 이를 감지하여 컴포넌트의 state.hasError 상태를 업데이트 합니다. render 메서드는 업데이트 된 hasError 값을 확인 조건 처리하여 오류가 발생한 경우와 그렇지 않은 경우를 나눠 렌더링 합니다.
class ErrorBoundary extends Component {
state = { hasError: null }
// 자식 컴포넌트의 오류를 throw한 후 실행
static getDerivedStateFromError(error) {
// throw된 오류가 감지되면, hasError 상태 값을 true 처리
return { hasError: error }
}
render() {
// 오류 발생 시, 오류 컴포넌트 렌더링
if (this.state.hasError) {
return <ErrorDisplay />
}
// 오류가 발생하지 않은 경우 자식 노드 렌더링
return this.props.children
}
}
componentDidCatch 메서드는 자식 컴포넌트 오류가 발생된 이후 실행됩니다. error, info 2개의 매개변수가 전달되며 info는 어떤 컴포넌트가 오류를 발생시켰는 지에 대한 정보를 가진 componentStack 속성을 가진 객체입니다.
class ErrorBoundary extends Component {
state = { hasError: false }
static getDerivedStateFromError(error) {
return { hasError: error }
}
// 자식 컴포넌트의 오류를 throw한 후 실행
componentDidCatch(error, info) {
// info 매개변수:
// 어떤 컴포넌트가 오류를 발생시켰는지에 대한 정보를 가진 componentStack 속성을 가진 객체
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
logComponentStackToService(info.componentStack)
}
render() {
if (this.state.hasError) {
return <ErrorDisplay />
}
return this.props.children
}
}