ReactJS - 컴포넌트 반복

ROCKBELL·2022년 12월 5일
0

리액트

목록 보기
8/12

Array.map()

arr.map(callback, [thisArg])


callback(crreuntValue[, index[, array]]) - 새로운 배열의 요소를 생성하는 함수

  • currentValue : 현재 처리하고 있는 요소
  • index : 현재 처리하고 있는 요소의 인덱스 값 (optional)
  • array : 현재 처리하고 있는 원본 배열 (optional)

thisArg - 콜백을 실행할때 this로 사용되는 값


key 설정

key 값을 이용하면 렌더링했을때 어떤 원소의 변동이 있는 지 쉽게 찾아 낼 수 있습니다

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>
      </>
    )
 }
profile
luv it

0개의 댓글