STUDY/React & React Native

[리액트] 에러 바운더리 (Error Boundary)_⚠ / react-error-boundary 라이브러리, Class로 직접 구현하기

ez1n 2022. 9. 15. 05:06

 

[React_ Error Boundary]

 

리액트에서 예외 발생 시 예외 페이지를 보여주는 방법에 대해 알아보자

 


 

<STUDY>

 

리액트로 예외 페이지를 생성하는 두 가지 방법을 알아보자.

 

⚠ 리액트 Lifecycle method를 이용하여 구현하기

 

   - errorBoundary.jsx

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>오류가 발생했습니다.</h1>;
    }

    return this.props.children; 
  }
}

 

   1. static getDerivedStateFromError() : 오류 발생 후 대체 UI 렌더링 

 

   2. componentDidCatch() : 오류 정보 기록

 

 

   - app.jsx

import React from 'react';
import Component1 from './component1';
import ErrorBoundary from './errorBoundary';

export default function App() {
  return (
    <ErrorBoundary>
      <Component1 />
    </ErrorBoundary>
  ) 
};

 

 

⚠ react-error-boundary 라이브러리 사용하기

 

   1. react-error-boundary 설치

npm install react-error-boundary

 

   2. 코드

import {ErrorBoundary} from 'react-error-boundary'

function ErrorFallback({error, resetErrorBoundary}) {
  return (
    <div>
      <p>오류가 발생했습니다.</p>
      <p>사유 :</p>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>다시 시도</button>
    </div>
  )
}

export default function App() {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <ComponentThatMayError />
    </ErrorBoundary>
  )
};

 


클래스 컴포넌트를 사용하지 않고 라이브러리를 통해 오류가 발견되면 사용자에게 Error UI를 보여주도록 간단하게 구현 가능하다.

 

<자세한 내용은 공식 홈페이지를 확인해 주세요.>

 

 

👉 https://reactjs.org/docs/error-boundaries.html

 

Error Boundaries – React

A JavaScript library for building user interfaces

reactjs.org

 

👉https://www.npmjs.com/package/react-error-boundary

 

react-error-boundary

Simple reusable React error boundary component. Latest version: 3.1.4, last published: a year ago. Start using react-error-boundary in your project by running `npm i react-error-boundary`. There are 504 other projects in the npm registry using react-error-

www.npmjs.com

 

 


 

내가 보려고 정리하는 리액트🔆

 

👉ez1n github 구경하기👈 

 

 

ez1n - Overview

Study -ing. ez1n has 9 repositories available. Follow their code on GitHub.

github.com