[React] 리액트 undefined처리 방법 (누구든지하는 리액트5편 공부정리)

728x90
반응형

* 이 글은 velopert.com/3631 을 공부하며 필요한 부분을 기록 정리한 글입니다.

 

 

렌더링 부분에서 오류가 발생하는 것 방지해 주는 방법 

 

에러가 나는 경우 

this.props.onClick(); // 존재하지 않는 함수를 호출시 에러
this.props.object.value; // object is undefined
this.props.array.length; // array is undefined // 배열이나 객체가 존재하지  않을 때

 

해결법

1. undefined의 경우를 처리해준다

render() {
  if (!this.props.object || !this.props.array || this.props.array.length ===0) return null;
  // object 나 array 를 사용하는 코드
}

2. defaultProps를 처리해준다

 컴포넌트이름.defaultProps = {
    onIncrement: () => console.warn('onIncrement is not defined'),
    object: {},
    array: []
  }

 

728x90
반응형
TAGS.

Comments