Encountered two children with the same key

Seonhee Kim·2023년 11월 6일

에러노트

목록 보기
8/11
Warning: Encountered two children with the same key, ``. 
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.

map 사용 시 key값에 (귀찮아서) index를 넣고는 했다. 그러다가 콘솔에서 워닝이 떠서 구글링해보니, 엘리먼트에 안정적인 고유성을 부여하기 위해서는 index를 넣는 방법은 안 좋다고 한다. 왜냐하면 리액트가 DOM 요소를 식별할 때는 key를 통해 식별하기때문에 변할 요소가 있는 index는 불안정적이기 때문에 ~_~

	<select
          className="outline-0 border-gray-200 border-[1px] rounded-2xl w-24 h-7 pl-2"
          onChange={(e) => setStart(Number(e.target.value))}
          defaultValue={start}
          key={start} 
        >
          {startArray.map((item, index) => {
            return (
              <option key={index} value={item}>
                {item}
              </option>
            );
          })}
	</select>

	<select
          className="outline-0 border-gray-200 border-[1px] rounded-2xl w-24 h-7 pl-2"
          onChange={(e) => setStart(Number(e.target.value))}
          defaultValue={start}
          key={start} 
        >
          {startArray.map((item, index) => {
            return (
              <option key={item.id} value={item}>
                {item}
              </option>
            );
          })}
	</select>


// 보통 이렇게하면 중복 키 값 에러는 없어지는 듯 하다.

하지만 내가 사용하던 item 요소에는 유니크값으로 사용할 수 있는 값이 없었고, 만들어서 코드를 돌려봤지만 에러가 없어지지 않았다.

어느 key에서 오류가 나는걸까 생각하다가 잘 보니 select에도 key 값이 있고 , 그 값이 내 이벤트에 의해 같은 값이 된다는 것을 알게 되었다. (시작과 끝 값이 같아질때 콘솔에 워닝이 떴다.)
select의 key는 사용중인 값이 아니었기때문에, 연산을 넣어서 두 값이 다르도록 설정했더니 워닝이 없어졌다.

key 값에 index를 넣는 일은 그만 해야겠다

profile
안녕하세요 ~_~

0개의 댓글