[React를 다루는 기술] 6장 - 컴포넌트 반복
😉 자바스크립트 배열의 map() 함수
- map()을 이용하여 반복 되는 컴포넌트를 렌더링
- 파라미터로 전달된 함수를 이용하여 배열 내 각 요소를 원하는 규칙에 따라 변환
- 결과로 새로운 배열을 생성한다.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
- callback : callback 함수
- currentValue: 현재 처리중인 요소
- index (옵셔널): 현재 처리중인 요소의 index 값
- array (옵셔널): 현재 처리하고 있는 원본 배열
- thisArg (옵셔널): callback 함수 내부에서 사용할 this 레퍼런스
😉 데이터 배열을 컴포넌트 배열로 변환하기
- 간단한 예시 코드 ```jsx import React from “react”;
const IterationSample = () => { const names = [“susan”, “colemann”, “walker”]; const nameList = names.map((name, index) => <li key={index}>{name}</li>);
return <ul>{nameList}</ul>; };
export default IterationSample;
## 😉 Key ##
- key는 컴포넌트 배열을 렌더링했을 때 어떤 원소에 변동이 있었는지 알아내려고 사용
- key가 없다면 Vitual DOM을 처음부터 끝까지 비교해야함.
1. key 설정
- 규칙 : key 값은 언제나 유일 ( 게시판이라면 게시판 번호가 key)
- 다음과 같이 수정
```jsx
const nameList = names.map((name, index)=>{
return <li key={index}>{name}</li>
})
- 위 처럼 고유한 값이 없을 때만 index를 key로 설정
- 초기 상태를 설계할 때 id도 같이 객체로 넣어서 설정
🐱🐉 특정 컴포넌트를 추가하고 삭제하기
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 });
setNames(nextNames);
setNextId(nextId + 1);
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;
Leave a comment