6.1 자바스크립트 배열의 map() 함수
arr.map(callback, [thisArg])
- callback : 새로운 배열의 요소를 생성하는 함수
- currentValue : 현재 처리하고 있는 요소
- index : 현재 처리하고 있는 요소의 index 값
- array : 현재 처리하고 있는 원본 배열
//map변환 예시
var numbers = [1, 2, 3, 4, 5];
var processed = numbers.map(function (num) {
return num * num;
});
console.log(processed);
//ES6
var numbers = [1, 2, 3, 4, 5];
var processed = numbers.map(num => num * num);
console.log(processed);
6.2 데이터 배열을 컴포넌트 배열로 변환하기, 6.3 key
고유한 값이 없을 때 index값을 key로 사용해야 함. 그러나, 이 경우 배열이 변경될 때 효율적으로 리렌더링 하지 못 함.
//key값을 설정해주지 않으면 콘솔에 에러 표시됨. Virtual DOM을 비교하는 과정에서 key로 변화를 빠르게 감지
import React from "react";
const IterationSample = () => {
const names = ['김', '이', '박', '최'];
const nameList = names.map((name, index) => <li key={index}>{name}</li>);
return <ul>{nameList}</ul>;
}
export default IterationSample;
6.4 응용
-
상태 안에서 배열을 변형할 때 배열에 직접 접근하여 수정하는 것이 아니라 concat, filter 등의 배열 내장 함수를 사용하여 새로운 배열을 만든 후 이를 새로운 상태로 설정해 주어야 한다.
-
배열 추가 시 push <-> concat : 불변성 X <-> O
-
배열 변경 시 pop <-> filter : 불변성 X <-> O
-
import React, {useState} from "react";
const IterationSample = () => {
const [names, setNames] = useState([
{id: 1, text: '김'},
{id: 2, text: '이'},
{id: 3, text: '박'},
{id: 4, text: '최'},
]);
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5);
const onChange = e => setInputText(e.target.value);
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text: inputText
})
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
};
const onRemove = id => {
const nextNames = names.filter(name => name.id !== id);
setNames(nextNames);
};
const nameList = names.map(name => (<li key={name.id} onDoubleClick={() => onRemove(name.id)}>{name.text}</li>));
return (
<>
<input value={inputText} onChange={onChange}/>
<button onClick={onClick}>추가</button>
<ul>{nameList}</ul>
</>
);
}
export default IterationSample;
'개발 도서 > 리액트를 다루는 기술(개정판)' 카테고리의 다른 글
8장 Hooks (0) | 2020.05.23 |
---|---|
7장 컴포넌트의 라이프사이클 메서드 (0) | 2020.05.23 |
5장 ref:DOM에 이름 달기 (0) | 2020.05.23 |
4장 이벤트 핸들링 (0) | 2020.05.22 |
3장 컴포넌트 (0) | 2020.05.17 |