[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
👉https://www.npmjs.com/package/react-error-boundary
내가 보려고 정리하는 리액트🔆
'STUDY > React & React Native' 카테고리의 다른 글
[리액트] 전역 state 관리하기_❓ / useReducer + ContextAPI, Redux와 차이점 (0) | 2022.11.15 |
---|---|
[리액트] input [type = 'file'] 중복 업로드 오류_⚡ (0) | 2022.10.23 |
[리액트] react-toastify 사용하기 / 알림창 띄우기 (0) | 2022.09.05 |
[리액트] PDF 프리뷰어 만들기, PDF 미리보기_📜 / react-pdf, 서버에서 받은 파일 미리보기 (0) | 2022.09.03 |
[리액트] Vite_proxy 설정하기_🐾 / 리액트 + Vite + TypeScript, axios, CORS 에러 (0) | 2022.08.29 |