[React] error 다루기(getDerivedStateFromError)

rondido·2022년 11월 14일
0

React

목록 보기
8/39
post-thumbnail

try catch문 처럼 리액트로 error를 다루고자 했다.

에러를 핸들링을 하고자 class component로 ErrorBoundary라는 class 생성

근데 왜 함수형 컴포넌트가 아닌 클래스형 컴포넌트로 만들었는가 하면

클래스형 컴포넌트에서 getDerivedStateFromError라는 함수를 제공

error를 받아서 화면에 보여준다.

Fallback은 Error가 났을때 보여줄 컴포넌트

<!DOCTYPE html>
<html lang="en">
  <body>
    <script
      crossorigin
      src="https://unpkg.com/react@16.7.0/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"
    ></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <div id="root"></div>

    <script type="text/babel">    
        const rootElement = document.getElementById("root");

        class ErrorBoundary extends React.Component{
            state = {error:null};
            static getDerivedStateFromError(error){
                return {error}
            }
            render(){
                const { error } = this.state;
                if(error){
                    return <this.props.fallback error={error} />;
                }
                return this.props.children;
            }
        }

        const Child = () =>{
            throw new Error('에러가 나타났다...');
            return <p>Child...</p>;
        }
        const Fallback = ({error}) =>{
            return <p>에러 함수입니다.</p>;
        }
        const App = () => {
          
            return (
                <>
                <p>App</p>
                <ErrorBoundary fallback={Fallback}>
                    <Child/>
                </ErrorBoundary>
                </>
            )
        }
        ReactDOM.render(<App />,rootElement);
    </script>
  </body>
</html>


ErrorBoundary라는 컴포넌트를 JSX문법으로 선언하여 Child 컴포넌트를 감싸줌으로써 에러가 발생되도 App을 그릴 수 있으며 에러가 났을때 console에서만 볼 수 있는 에러들을 직접 화면으로 그려주어 에러가 났는것을 확인 할 수 있다.

profile
개발 옆차기

0개의 댓글