-
Error / React / Uncaught TypeError: Cannot read properties of null (reading 'map') 문제해결 / aixos 데이터 렌더링Web dev/Error 2022. 4. 14. 23:59728x90반응형
리엑트로 퍼블리싱중이다.
json-server로 api를 만들어서 불러와 슬라이드를 만들고 있었다.
데이터를 잘 받아와서 map()함수로 데이터를 뿌려주려고 했는데
에러가 났다..
Uncaught TypeError: Cannot read properties of null (reading 'map')
검색을 해보니 이러한 에러가 발생한 이유는 React 는 렌더링이 화면에 커밋 된 후에야 모든 효과를 실행하기 때문이다.
즉 React는 return에서map()을 반복실행할 때 첫 턴에 데이터가 아직 안들어와도 렌더링이 실행되며 당연히 그 데이터는 undefined로 정의되어 오류가 나는 것이다.
문제해결은 &&을 넣어준다.
{car && car.map((car) => ( <SwiperSlide key={car.id}> {car.name} </SwiperSlide> ))}
조건이 참이면 실행하고 거짓이면 넘어가기 때문에 데이터가 undefined 이면 map()함수를 실행하지 않는다.
728x90반응형'Web dev > Error' 카테고리의 다른 글