React
[리액트/에러해결] Warning: Each child in a list should have a unique "key" prop 해결방법
메이플 🍁
2022. 4. 7. 14:24
⚠️ 에러내용

원문
Warning: Each child in a list should have a unique "key" prop.
해석
리스트 안에 있는 각각의 자식 요소가 유니크한 key를 가져야한다.
❓ 에러발생이유
리액트에서 map을 사용해 리스트를 만들때 각 리스트에 식별자로서 key값을 부여해야한다. 리액트는 key를 사용해서 어떤 요소가 변경되었는지를 파악한다.
❗️ 해결방법
map을 사용해 리스트를 만들때 key값을 부여해준다. 일반적으로 key값으로 id를 많이 사용하지만 key값으로 마땅한 데이터가 없다면 index를 key값으로 지정해줄 수도 있다.
index를 key값으로 지정한 예제
import React from 'react';
class RefClass extends React.Component {
constructor(props) {
super(props);
this.state = {
bucketlists: ['영화관 가기', '매일 책읽기', '수영 배우기'],
};
}
render() {
return (
<>
<h1>내 버킷 리스트</h1>
<hr />
{this.state.bucketlists.map((bucketlist, index) => (
<p key={index}>{bucketlist}</p>
))}
</>
);
}
}
export default RefClass;