undefined
Error Boundary - React 본문
반응형
1. 오류 경계란?
- 오류가 일어났을 때 웹사이트를 중지시키지 않고 에러관리를 할 수 있도록함.
- 기본 자바스크립트 try and catch와 유사함
- 일종의 컴포넌트
- 함수형 컴포넌트에서는 이용이 불가하므로 class 컴포넌트로 사용되야함.
2. 사용 이유?
- 자바스크립트의 try and catch를 이용한다면 물론 오류 관리가 되겠지만 그 범위는 해당 컴포넌트에 국한됨.
- 오류경계 컴포넌트로 관리하고 싶은 컴포넌트를 감싸준다면 하위트리에 있는 모든 오류를 관리 가능하게함.
3. 사용 방법
(1). import Component
import {Component} from 'react'
(2). class 컴포넌트 생성
class ErrorBoundary extends Component {
construct() {
super();
}
render() {
return this.props.children;
}
}
export default ErrorBoundary;
Context.Provider 처럼 감싸주는 컴포넌트이기 때문에 props.children 리턴
(3). componentDidCatch 사용
componentDidCatch(err) {
console.log(err);
}
이 함수를 써줘야 react가 errorBoundary임을 인지한다.
(4). state 이용하기
class ErrorBoundary extends Component {
construct() {
super();
this.state = { hasError: false };
}
componentDidCatch(err) {
console.log(err);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <p>Error</p>;
}
return this.props.children;
}
}
export default ErrorBoundary;
에러가 발견되면 hasError state => true로 변경
hasError가 true일때 pTag 출력
(5). wrapping 해주기
<ErrorBoundary>
<SomeThing/>
</ErrorBoundary>
반응형
'React' 카테고리의 다른 글
useReducer -React (0) | 2022.06.23 |
---|---|
UseEffect -React (0) | 2022.06.23 |
Ref - React (0) | 2022.06.22 |
Portal -React (0) | 2022.06.22 |
Comments