리액트 에러처리

서울IT코드정리 /kyChoi·2021년 11월 17일
0

리랙트

목록 보기
12/18
 <script type="text/babel">
      class ErrorBoundary extends React.Component {
        state = { error: null };
        static getDerivedStateFromError(error) {
          return { error };
        }
        render() {
          const { error } = this.state;
          if (error) {
            return <p> There is some error..</p>;
          }
          return this.props.children;
        }
      }
      const Child = () => {
        throw new Error("Something wrong....");
        return <p>I am a Child</p>;
      };
      const App = () => {
        return (
          <>
            <p>App</p>
            <ErrorBoundary>
              <Child />
            </ErrorBoundary>
          </>
        );
      };
      ReactDOM.render(<App />, document.getElementById("root"));
    </script>

App 컴포넌트를 실행하는데, Child 컴포넌트에서 throw new Error 를 했다, 이럼 App에 있는 모든게 동작하지 않는다, 동작을 하되, 에러가 낫음을 보여주자
ErrorBoundary 클라스를 만들어서 state 객체를 만들었따, error : null 이다 static getDerivedStateFromError(error) 이 클라스는 외워야 할듯

여기서 fallback 을 사용해서 ErrorBoundary 에 직접 값을 입력 할 수 있다.

 if (error) {
            return <p> this.props.fallback;
            
            
<ErrorBoundary fallback={<p>something goes wrong..</p>}>
              <Child />
</ErrorBoundary>

또는 Fallback 컴포넌트를 만들어 줄수 있다.

 const Fallback = () => {
        return <p>There is some Error! </p>;
      };

      const App = () => {
        return (
          <>
            <p>App</p>
            <ErrorBoundary fallback={<Fallback />}>
              <Child />
            </ErrorBoundary>
          </>
        );
      };
profile
건물주가 되는 그날까지

0개의 댓글