React- Error 처리 맛보기

GoGoDev·2021년 11월 3일
0

React

목록 보기
3/3
post-thumbnail

ErrorBoundary : child컴포넌트에서 에러 발생 시, 특정한 화면을 보여준다.

App 컴포넌트에는 에러가 없지만 Child 컴포넌트에 에러가 있을 시 사용해보자.

class ErrorBoundary extends React.Component {
	state = {error: null};
    static getDerivedStateFromError(error) { // static getDerivedStateFromError을 사용하기 위해 class 컴포넌트를 사용
    	return {error}
    }
    
    render() {
    	const {error} = this.state;
        if (error) {
        	return <this.props.fallback error={error} />  //this.props.fallback;
        }
        
        return this.props.children;
    }
}

const Fallback = ({error}) => {
    return <p>{error.message}</p>
}

error을 핸들링하고 싶은 컴포넌트를 클래스 컴포넌트인 ErrorBoundary로 감싼다.

<ErrorBoundary fallback={Fallback}> // fallback으로 특정 컴포넌트를 준다
	<Child />
</ErrorBoundary>

기존에 Error가 없는 화면은 그대로 보여주고 Error가 발생한 화면에는 There is some Error...라는 문구를 표시한다.

Error Boundary = Catch Error 해서 보여준다
Fallback = 백업 플랜, Error가 났을 때, 보여줄 컴포넌트

profile
🐣차근차근 무럭무럭🐣

0개의 댓글