230619 개발일지 TIL - Warning: Each child in a list should have a unique "key" prop.

The Web On Everything·2023년 6월 19일
0

개발일지

목록 보기
37/269

TodoList 작업 중 생긴 오류

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

Check the render method of `App`. See https://reactjs.org/link/warning-keys for more information.
    at div
    at App (http://localhost:3000/main.fb8b72ff6973ef8cb461.hot-update.js:28:76)
{todos.map(function (todo) {
  return (
    <div
      style={{
        border: "1px solid black",
        margin: "10px",
        paddingLeft: "10px",
      }}
      >
      <p>{todo.id}</p>
      <h3>{todo.title}</h3>
      <p>{todo.contents}</p>
      <p>{todo.isDone.toString()}</p>
    </div>
  );
})}

원인
항상 map 메소드를 쓸 때 발생하게 된다.

해결방법
1. 항상 최상위 컴포넌트 html 요소가 key가 가지고 있는 아이디를 부여

{todos.map(function (todo) {
  return (
    <div
      key={todo.id}
      style={{
        border: "1px solid black",
        margin: "10px",
        paddingLeft: "10px",
      }}
      >
      <p>{todo.id}</p>
      <h3>{todo.title}</h3>
      <p>{todo.contents}</p>
      <p>{todo.isDone.toString()}</p>
    </div>
  );

2. 2번째 인자로는 index를 항상 반환을 해줌, 그래서 index를 key값에 넣어주는 방법(권장되지 않는 방법)

{todos.map(function (todo, index) {
  return (
    <div
      key={index}
      style={{
        border: "1px solid black",
        margin: "10px",
        paddingLeft: "10px",
      }}
      >
      <p>{todo.id}</p>
      <h3>{todo.title}</h3>
      <p>{todo.contents}</p>
      <p>{todo.isDone.toString()}</p>
    </div>
  );
})}

2번 방법이 권장되지 않는 이유

index 값도 변경되므로 리스트의 순서가 변경되거나 요소가 추가,제거될 때 문제를 발생 시킬 수 있다.

느낀 점
map함수를 사용할 때 key값에 고유 ID나 식별자를 key로 사용해야겠다고 생각했다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글