"Warning: Each child in a list should have a unique "key" prop "

란이:)·2023년 7월 28일
0

error

목록 보기
19/19

첫번째 에러

<div>{user.map(value => (
      <div>{value.head.name}</div>
    ))}</div>

문제점

Warning: Each child in a list should have a unique "key" prop

<div>{user.map(value => (
      <div key={value}>{value.head.name}</div>
    ))}</div>

해결방법

react에서 map함수로 배열을 JSX 리스트로 구현할때 key prop을 자식 컴포넌트마다 넣어줘야 한다. 그리고 index로 넣어주는 건 지양해야 한다. 배열의 원소의 순서가 바뀔때마다 index와 컴포넌트마다 고유해야 하는 key값이 같이 바뀌기 때문!



이어서 나온 에러

<div>{user.map(value => (
      <div key={value}>{value.head.name}</div>
    ))}</div>

문제점

Warning: Encountered two children with the same key, {value}. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

<div>{user.map(value => (
     <div key={value.id}>{value.head.name}</div>
   ))}</div>

해결방법

콘솔을 찍어보니 user는 객체였다. 객체는 key 값이 되면 중복될 수 있으므로 고유하게 지정해줘야 한다.

profile
FE Developer 🐥

2개의 댓글

comment-user-thumbnail
2023년 7월 28일

좋은 정보 얻어갑니다, 감사합니다.

1개의 답글