Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 카카오맵 api
- 알고리즘
- web3-react
- CSS
- 메일 보내기 react
- 카카오지도 구현
- use Client
- pass인증
- 사이트맵
- nextjs 메일보내기
- 프론트 본인인증
- 전체 너비로 css
- next15
- App Router
- nextjs
- 빈도수세기
- nextjs contact us
- react swiper
- robots.txt
- 다중포인터
- Next.js 나이스 본인인증
- React 나이스 신원인증
- 함수
- github
- 프로그래머스
- JavaScript
- react
- swiper
- Til
- 구글 메일보내기
Archives
- Today
- Total
YEV.log
React 에러 | Type Error: Cannot read properties of undefined (reading '0') 본문
Web/Error
React 에러 | Type Error: Cannot read properties of undefined (reading '0')
일렁이는코드 2022. 2. 6. 17:33 TypeError: Cannot read properties of undefined (reading '0')
API 통신 전에 Mock data로 작업하는 중에 number 형식의 배열을 가져와 React JSX 형식의 텍스트로 요소 하나씩 뿌려주는 부분에서만 에러가 났다. 단순한 number나, string 형식은 문제없이 보이는데 arrayData[0], arrayData[1] 이렇게 요소 하나씩 접근하는 부분에서 undefined 에러가 났다.
🚧 받아오는 데이터 형식과 JSX
문제는 "pair_profit" 배열이다. 🤦🏻♀️
{
"data": {
"id": "1",
"max_price": 51200000.333,
"min_price": 40000000.333,
"pair_profit": [0.00043, 0.00089]
}
}
<p>
{resultData.pair_profit[0]} % ~
{resultData.pair_profit[1]} %
</p>
🚧 해결 방법
{resultData.pair_profit && (
<p>
{settingResultData.pair_profit[0]} % ~
{settingResultData.pair_profit[1]} %
</p>
)}
리액트에서 배열 관련 undefined 에러는 거의 jsx에서 조건부렌더링을 사용하지 않아서이다. 미리 useState에 데이터를 저장하는 경우 경우, 데이터가 제대로 불러오기 전 [undefined,undefined] 이런 식으로 요소가 undefined로 들어가는 세팅되기도 하는데 이때 데이터 값이 세팅되기 전에 읽으려 해서 undefined typeerror 가 난다.
결론: 조건부렌더링을 잘 적용해주자!
🚧 결과 화면

반응형
'Web > Error' 카테고리의 다른 글
Typescript 에러 | 객체의 key를 변수(객체키)로 접근 하기 (0) | 2022.07.16 |
---|---|
Typescript 에러 | 모듈 '~~~~'에 대한 선언 파일을 찾을 수 없습니다. 해결 방법 (0) | 2022.07.13 |