[TIL #29] React - Westagram Mission 5
📚 Mission 5) map 함수 적용시 key props를 부여하는 이유
인스타그램 클론 개인 프로젝트(westagram) 진행하면서 feed에 달리는 Comment를 map method를 이용하여 props를 통하여 data를 구현 하는 연습을 해보았다.
:: 댓글 부분 <span>
에 map method를 이용하여 ID, Message, time을 를 띄우고자 했다.
<처음 구현한 Code>
<div className="commentPlus">
{this.state.replyDatas.map(element => {
const { id, reply, time } = element;
return (
<CommentInputList id={id} reply={reply} time={time} />
);
})}
</div>
<div id="typeComment">
{this.state.commentList.map(commentInfo => {
return (
<CommentInput
id={commentInfo.id}
time={commentInfo.time}
comment={commentInfo.comment}
/>
);
})}
👇<Key 값 포함 수정된 code>
<div className="commentPlus">
{this.state.replyDatas.map(element => {
const { id, reply, time } = element;
return (
<CommentInputList key={id} id={id} reply={reply} time={time} />
);
})}
</div>
<div id="typeComment">
{this.state.commentList.map(commentInfo => {
return (
<CommentInput
key={commentInfo.id}
id={commentInfo.id}
time={commentInfo.time}
comment={commentInfo.comment}
/>
);
})}
🖐잠시) 구조 분해 할당이란?
배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 javascript 표현식이다const obj = { name = "joonhyun" gender = "man" } const {name, gender} = obj console.log(name) //joonhyun console.log(gender) // man
위 처럼 구조분해 할당을 사용하면 위처럼
joonhyun
출력하기 위해obj.name
을 사용하지 않고name
만 사용하여 값을 불러 올 수 있다.
key값을 쓰지않아도 댓글 구현에는 큰 무리는 없다.
하지만 브라우저 콘솔창에 아래와 같은 warning이 뜨게 된다.
이유는 map을 통해 반복되어 찍히는 배열의 값이 구분되어지는 것 없이 return되어지기 때문이다.
💡 key는 배열 형태를 map매서드로 변환할때 꼭 써줘야하는 값이다
map매서드 안에 (ex)li) 배열끼리 엉키지않게 해당 map의 배열만이 갖는 유니크한 고유값 (ex)index) 넣어주는 것이다.
= 결국 key값도 {userId}/{content}와 같이 반복하니까 배열이 길어질수록 key에 해당하는 id값은 계속 늘어난다.
(반복되어 늘어나는 id값에 대한 해석은 클론코딩 전체 코드리뷰에서 확인!)
📍결과적으로
React의 re-render시에 효율성을 위해서 key값을 부여해야 한다.
index값은 배열의 요소가 어디에 추가되느냐에 따라서 가변적일 수 있기에 해당 요소가 가지고 있는 "특정하고 유일한 값"을 이용하는 것을 권장한다.
Author And Source
이 문제에 관하여([TIL #29] React - Westagram Mission 5), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@junchi211/TIL-29-React-Westagram-Mission-5저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)