arr.map(callback, [thisArg])
callback(crreuntValue[, index[, array]])
- 새로운 배열의 요소를 생성하는 함수
thisArg
- 콜백을 실행할때 this로 사용되는 값
key 값을 이용하면 렌더링했을때 어떤 원소의 변동이 있는 지 쉽게 찾아 낼 수 있습니다
const IterationSample = () => {
const [names, setNames] = useState([
{ id :1 , name : '눈사람'},
{ id :2 , name : '얼음'},
{ id :3 , name : '눈'},
{ id :4 , name : '바람'},
])
return(
<>
<ul>
{names.map((name) =><li key={name.id}>{name.name}/li>)}
</ul>
</>
)
}
const IterationSample = () => {
const [names, setNames] = useState([
{ id :1 , name : '눈사람'},
{ id :2 , name : '얼음'},
{ id :3 , name : '눈'},
{ id :4 , name : '바람'},
])
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5);
const onChange = (e) => setInputText(e.target.value);
const onClick = (e) => {
/*
배열을 추가할때 concat 메서드 사용
원본 배열을 변경하지 않고 새 배열을 반환해 줘야 합니다
불변성 유지를 통해 컴포넌트의 성능을 최적화 할 수 있습니다
*/
const nextNames = names.concat({
id : nextId,
name : inputText,
})
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
}
const onRemove = (id) => {
/*
배열을 제거할때 filter 메서드 사용
원본 배열을 변경하지 않고 새 배열을 반환해 줘야 합니다
불변성 유지를 통해 컴포넌트의 성능을 최적화 할 수 있습니다
*/
const filteredNames = names.filter((name) => name.id !== id);
setNames(filteredNames);
}
return(
<>
<ul>
{names.map((name) => (
<li key={name.id} onClick={() => onRemove(name.id)}>{name.name}/li>
))}
</ul>
<input value={inputText} onChange={onChange} />
<button onClick={onClick}>추가</button>
</>
)
}