arr.map(callback, [thisArg])
์ด ํจ์์ ํ๋ผ๋ฏธํฐ๋ ์ด์ ๊ฐ๋ค.
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);
//๐์ด๋ฒคํธ ํธ๋ค๋ง e.target.value๋ ํ์ฌ DOM ๊ฐ
const onChange = e => setInputText(e.target.value);
const onClick = () => { //ํด๋ฆญ
const nextNames = names.concat({
๐//concat : ์๋ก์ด ๋ฐฐ์ด ๋ง๋ค์ด์ค๋ค.
๐//push : ๊ธฐ์กด ๋ฐฐ์ด ์์ฒด๋ฅผ ๋ณ๊ฒฝํด์ค๋ค.
id:nextId,
text:inputText
});
๐ํด๋ฆญ๋๊ณ ๋๋ฉด nextId์ 1์ถ๊ฐ, nextNames ์ด๋ฆ์ผ๋ก ๋์ฒด, setInputText ๊ณต๋ฐฑ์ฒ๋ฆฌ
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
};
//๐filter : ๋ถ๋ณ์ฑ์ ์ ์งํ๋ฉด์ ๋ฐฐ์ด์ ํน์ ํญ๋ชฉ์ ์ง์์ค๋ค. (๋ฐฐ์ด ๋ด์ฅ ํจ์)
๐filter ์ฌ์ฉํ๋ฉด ํน์ ์์๋ง ์ ์ธ์ํฌ ์ ์๋ค.
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;