[React] Map을 이용한 컴포넌트 나열하기

UkiUkhui·2021년 10월 9일

React 공부중

목록 보기
4/25

사실 내장함수는 잘 모른다
map에 대해 좀 더 자세히 적어놓고 나중에 더 좋은 내용 있으면 추가하는 식으로 해야겠다.

Map이란

파라미터로 전달된 함수를 이용해 배열 각 요소를 원하는 규칙에 따라 변환해 새로운 배열을 생성하는 것.

arr.map(callbackFunction(currentValue, index, array), thisArg);
  • currentValue : 현재 배열 내의 값
  • index 배열의 인덱스
  • array : 현재 배열
  • thisArg : callbackfunction 내에서 사용할 this 레퍼런스

map 사용 예제

const n = [1,2,3,4,5]
const arr = n.map((n) => n*n);
//[1,4,9,16,25]

Key값

  • 렌더링 시 컴포넌트 배열의 변화를 빠르게 알 수 있음
  • 컴포넌트 배열을 렌더링 했을 때, 어떤 원소에 변동이 있었는지 알아내기 위해 사용
  • 예) key 없을 때 : Virtual DOM 비교하는 과정에서 리스트를 순차적으로 비교하면서 변화 감지
const it = () => {
	const n = ["a", "b", "c"];
    const nlist = n.map((name) => <li>{name}</li>);
    return <ul>{nlist}</ul>;

}//key props 없다는 경고!

Key값 설정하기

  • map의 callback함수에서 props 사용하듯이 사용하면 됨
  • key값은 언제나 유일함
const aList = a.map((art) => {
	<Art
    		title={art.title}
        	writer={art.writer}
        	key={art.id}
       />
}
    
const it = () => {
	const n = ["a", "b", "c"];
    const nlist = n.map((name, index) => <li key={index}>{name}</li>);
    return <ul>{nlist}</ul>;

}//키값이 따로 없으므로 index 사용(비효율적)
profile
hello world!

0개의 댓글