• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

componentDidCatch에 관련된 질문입니다.

18.09.27 15:32 작성 조회수 90

0

componentDidCatch 를 사용할때

getBoundingClientRect 을 호출하게 되면..

this를 찾을 수 없어서 그런지..

오류를 내면서 componentDidCatch 도 호출이 안됩니다.

이런 경우는 어떻게 처리를 해야하는건가요?

  componentDidMount() {

console.log(this.myDiv.getBoundingClientRect().height);

}

componentDidCatch(error, info) {

console.log(error); //에러내용

console.log(info); //에러발생지

this.setState({

error: true

});

답변 1

답변을 작성해보세요.

0

꽃갈피님의 프로필

꽃갈피

2018.12.09

안녕하세요 :) 질문하신지도 오래 지났고, 제 방법이 맞는지도 모르겠지만 저도 질문자님과 같은 상황을 겪었던 터라 제가 해결했던 방법을 공유해서 이와 같은 문제를 겪는 분들에게 도움이 되었으면 하는 마음에 답변글을 답니다.

저는 componentDidCatch() 메서드가 component에서 발생한 에러를 해결해주는 것이라고 생각하여 자바스크립트 에러인 cannot read property 'getBoundingClientRect' of undefined 를 해결해주지 못하고 자바스크립트 에러때문에 componentDidCatch()도 호출이 되지 않은 것이라고 생각했습니다.

그래서 저는 구글링하여 다음과 같은 소스코드로 에러를 해결했습니다.

componentDidMount() {

console.log('componentDidMount');

function getSafe(fn) {

try {

return fn();

} catch (e) {

return undefined;

}

}

console.log(getSafe(() => this.myDiv.getBoundingClientRect().height));

}

try-catch문을 사용했는데 그럼 cannot read...관련 에러도 해결이 되고, componentDidCatch메서드도 호출이 되어서 화면에 '오류 났어요!'문구도 나타나게 됩니다.