TypeError: Cannot read properties of undefined (reading 'length')troubleshooting2023. 12. 21. 13:15
목차
서론
이번 블로그 글에서는 Firebase Hosting을 사용하는 도중 마주한 메인 화면이 빈 화면으로 나오는 이슈와 이를 해결하는 과정을 다루겠다. 문제는 프로젝트 파일 내부에서 발생하는 것으로, 로컬에서는 잘 작동하지만 배포된 도메인에서만 발생했다.
이는 로컬 환경과 배포 환경 간의 차이로 인한 문제로 의심되었고 다른 페이지에서는 모든 기능이 정상 작동하는데, 메인 화면에서만 이슈가 발생하는 점, '/' 경로에서만 화면이 나오지 않는 현상을 보고 다음과 같은 가설을 세울 수 있었다.
- route path 설정이 담긴 app.tsx 파일에 문제가 있을 것이다.
- MainPage만 나오지 않는 것이니 MainPage 관련 컴포넌트에서 에러가 있을 것이다.
둘 다 체크를 해보았고, MainPage 컴포넌트 문제가 맞았었다. 배포된 메인 페이지에서는 다음과 같은 에러 메세지가 기록되었다.
오류 메시지
TypeError: Cannot read properties of undefined (reading 'length')
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
length 함수 관련 문제인 것 같다. MainPage에서 length 함수를 사용하는 부분을 살펴보자.
오류 코드
const numPages = Math.ceil(probs.length / limit); // pagination 개수
...
if (probs?.length > 0) { //검색결과가 있는 경우
...
}
...
if (searchTerm !== null && searchTerm.length !== 0) {
setProbs(initPrbos.filter((element) => element.name.includes(searchTerm ? searchTerm : "")))
...
}
길이를 재고자 하는 변수의 값이 없는 경우를 체크하지 않고 그대로 올리고 있었다.
해결코드
const numPages = Math.ceil((probs?.length || 0) / limit); // pagination 개수
...
if ((probs?.length || 0) > 0) { //검색결과가 있는 경우
...
}
...
if (searchTerm !== null && searchTerm.trim().length !== 0) {
setProbs(initPrbos.filter((element) => element.name.includes(searchTerm.trim())));
...
}
Ways in which things go right are special cases of the ways in which things go wrong.
일이 잘 풀리는 것은 일이 잘못되는 경우 중에서 아주 특별한 경우이다.
728x90
반응형
LIST
'troubleshooting' 카테고리의 다른 글
@kdj :: Childev'note
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!