[Error] Uncaught TypeError: Cannot read properties of undefined (reading 'map')

박준석·2024년 4월 20일

Error

목록 보기
7/10
post-thumbnail

에러발생

프로젝트를 진행하던 중 에러가 하나 발생했다.

{movieDetail.genres && movieDetail.genres.map((item)=>(
   <Badge bg="danger"><li>{item && item.name}</li></Badge>
))}

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

에러를 확인하기 위해서 console.log를 찍어봤다.

console.log을 해봤을 때는 잘 나오는데 새로고침을 하면 에러가뜬다.

에러원인

그 이유는 React 는 렌더링이 화면에 커밋 된 후에야 모든 효과를 실행하기 때문이다.

Reactreturn에서 user.map(...)을 반복실행할 때 첫 턴에 데이터가 아직 안들어와도 렌더링이 실행되며 당연히 그 데이터는 undefined로 정의되어 오류가 나는 것이다.

해결방안

바로 조건부 렌더링 && 을 이용하는 것이다.

{movieDetail.genres && movieDetail.genres.map((item)=>(
      <Badge bg="danger"><li>{item && item.name}</li></Badge>
  ))}

true && expression은 항상 expression으로 실행되고 false && expression은 항상 false로 실행된다.

따라서 조건이 참이면 && 바로 뒤의 요소가 출력에 나타난다. 거짓이면 React는 무시하고 건너뛴다.

profile
느리지만 탄탄한 개발자 1명 빠른 개발자 10명 안부럽다.

0개의 댓글