map()
๋ฐฐ์ด ๋ด์ ๋ชจ๋ ์์ ๊ฐ๊ฐ์ ๋ํ์ฌ ์ฃผ์ด์ง ํจ์๋ฅผ ํธ์ถํ ๊ฒฐ๊ณผ๋ฅผ ๋ชจ์ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๋ ๋ฉ์๋์ด๋ค.์๋ฅผ ๋ค์ด
let arr = [ 1, 2, 3, 4, 5] ์ผ ๋,
arr.map ( num => num + 1 )arr์ ๋ชจ๋ ์์๋ง๋ค num + 1์ด ์ ์ฉ๋์ด ๊ฒฐ๊ณผ๊ฐ์ [ 2, 3, 4, 5, 6 ]์ด๋ค.
map() ๋ฉ์๋์๋ key ๊ฐ์ด ์กด์ฌํด์ผ ํ๋๋ฐ, key๊ฐ์ ์ง์ ํ์ง ์์ผ๋ฉด ๊ธฐ๋ฅ์์ ๋ฌธ์ ๋ ์์ง๋ง ๋ด๋ถ์ ์ผ๋ก ๋ค์ ๋ ๋ํ ๋์ ์๋ณ ๋ฌธ์ ๊ฐ ์๊ธด๋ค.
๋ณดํต key ๊ฐ์ ๊ณ ์ ํ ๋ฒํธ๋ก ์๋ณํ๊ธฐ ์ฝ๋๋ก id ๋ฒํธ๋ฅผ ์ฌ์ฉํ๋ค.
{commentList.map((comment) => { return ( <Comment key={comment.id} comment={comment.content} clickEvent={this.changeColor} name={comment.userName} /> ); })}
// ์ ๋ ฅํ ๋๊ธ์ด ์ถ๊ฐ๋ ๋ฐฐ์ด commentList์ mapping์ ์งํํด ์์ ์ปดํฌ๋ํธ(child) ํ๊ทธ์ key ๊ฐ์ผ๋ก comment.id๋ฅผ ์ง์ ํ๋ค.
// ์ฌ๊ธฐ์ comment๋ ๋ฐฐ์ด์ ๊ฐ ์์์ด๊ณ , id๋ Data ํ์ผ์ ํ ๋นํ ๊ณ ์ ๋ฒํธ์ด๋ค.[{ "id": 1, "userName": "wecode", "content": "Welcome to world best coding bootcamp!", "isLiked": true }, { "id": 2, "userName": "joonsikyang", "content": "Hi there.", "isLiked": false }]
// ์๋ mock data ์ผ๋ถ.
const newComment = [
{
id: this.state.commentList.length + 1,
userName: "rious275",
content: [this.state.iptCommentValue],
isLiked: true,
},
];
this.setState({
commentList: this.state.commentList.concat(newComment),
iptCommentValue: "",
});
// ๊ณ์ํด์ ์ถ๊ฐ๋ ๋๊ธ์ ์๋ก์ด id๋ฅผ ๋ถ์ฌํ๊ธฐ ์ํด length๋ฅผ ํ์ฉํ๋ค.
// newComment๋ ๊ธฐ์กด json ๋ฐ์ดํฐ์ ์ผ์นํ๋๋ก ์์ฑํ์ฌ ์์คํ
์ด ์ธ์ํ๋๋ก ๋ง๋ ๋ค.
// ๊ณ์ํด์ ์ถ๊ฐ๋ ๋๊ธ ๋ฐฐ์ด์ธ newComment๋ฅผ ๋ณ์๋ก ์ ์ธํด setState๋ฅผ
ํ์ฉํ์ฌ ๋๊ธ ๊ฐ์ ์ ์ฉ(newComment)ํ์ฌ commentList์ ๋ฃ๋๋ค.
๋ฐ์ ํ์ ๋ค์ ๋๊ธ ์
๋ ฅ์ฐฝ์ ์ด๊ธฐํ ๋์ด์ผ ํ๋ฏ๋ก ๋น ๊ฐ์ธ ""์ ์ค๋ค.