
JS 배열의 빌트인 메서드로, 해당 배열에 map 메소드를 실행시켜 파라미터로 함수를 전달하면, 해당 함수가 요소 순회를 한뒤에 새로운 배열을 만든다
// 반복되는 코드를 만드는 함수
function User({user}){
<div>
<b> {user.username} </b> <span> {user.email} </span>
</div>
}
// user라는 이름의 배열 리스트(컴포넌트안에 만들어져 있다하자)
.....
//
reder(){
user.map(user => (<User user = {user})
}
이렇게 하면 기존 user 배열에 map 을 이용해서 user(기존 리스트)를 파라미터로 주고, 반복되는 코드를 만들는 함수인 User를 호출면서 파라미터로 user(user리스트의 한 요소를 준다)을 주는 화살표 함수를 만들어
배열을 새로 랜더링 할수있게 만들었다.
배열에 key가 없다면 에러가 날것이다.(태그에 Key를 넣어야한다)
디폴트는 idex값으로 파라미터를 주기도 하지만
지금 user라는 배열에 user.id가 있으니 이를 파라미터로 지정해주면 된다.
concat 함수를 이용 ⇒ 후에 스프레드 문법을 이용하면 더욱 불변성을 유지하면서 추가할수 있다
import React, { useState } from 'react'
function IterationSample() {
const [name, setName] = 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 newNames = name.concat({
id: nextId,
text: inputText
});
setNextId(nextId + 1)
setName(newNames)
setInputText('')
}
const nameLsit = name.map(name => <li key={name.id}>{name.text}</li>)
return (
<div>
<input
value={inputText}
onChange={onChange}
/>
<button
onClick={onClick}
>추가</button>
<ul>{nameLsit}</ul>
</div>
)
}
export default IterationSample;
이처럼 기존 상태를 유지하면서, 새로운 배열을 만드는것을 불변성 유지 라고 한다
마찬가지로 불변성을 유지하면서 업데이트
filter 함수를 사용한다. ⇒ 특정 조건에 만족하는 원소들만 필터해서 거침, filter함수 인자에 분류하고 싶은 조건을 반환하는 함수를 넣어주면 된다.
import React, { useState } from 'react'
function IterationSample() {
const [name, setName] = 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 newNames = name.concat({
id: nextId,
text: inputText
});
setNextId(nextId + 1)
setName(newNames)
setInputText('')
}
const onRemove = id => {
const newNames = name.filter(name => name.id !== id);
setName(newNames)
}
const nameLsit = name.map(name => <li key={name.id} onDoubleClick={() => onRemove(name.id)}>{name.text}</li>)
return (
<div>
<input
value={inputText}
onChange={onChange}
/>
<button
onClick={onClick}
>추가</button>
<ul>{nameLsit}</ul>
</div>
)
}
export default IterationSample;