https://youtu.be/x3rhCJWGFc4 를 보며 공부하고, 이해하기 위해 정리 중입니다.
map() 메소드는 파라미터로 전달 된 함수를 통하여 배열 내의 각 요소를 처리해서 그 결과로 새로운 배열을 생성합니다.
사용 문법
arr.map(callback, [thisArg])
callback 새로운 배열의 요소를 생성하는 함수로서, 다음 세가지 인수를 가집니다.
currentValue 현재 처리되고 있는 요소
index 현재 처리되고 있는 요소의 index 값
array 메소드가 불려진 배열
thisArg (선택항목) callback 함수 내부에서 사용 할 this 값을 설정
Ex)
let numbers = [1,2,3,4,5];
let result = numbers.map((num) => {
return num*num;
});
결과값: [1, 4, 9, 16, 25]
똑같은 원리로 배열을 매핑 할수 있다.
데이터 배열을 렌더링 할때는 map으로 간단하게.
render() {
const mapToComponents = (data) =>{
return data.map((contact, i)=>{
return(<ContactInfo contact={contact} key={i}/>)
})
};
return(<ContactInfo contact={contact} key={i}/>) ;
에서 key 를 포함 하는 이유는 리액트에서는 array에서 키로 아이템을 identify 해서 어떤 아이템의 상태변화가 있을때, 바로 알 수 있게 한다고 한다.
(참조: https://reactjs.org/docs/lists-and-keys.html#keys )
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
${number}
</li>
);
가장 좋은 방법은 아이템에 유니크한 id를 키로 부여하는 방법이다 (id가 있다면)
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);
아이템의 정렬 순서가 바뀔지도 모르기 때문에 인덱스를 키로 사용하는걸 권장하지 않는다. 하지만 key를 설정하지 않으면 default로 인덱스를 키로 사용한다.