React

State에 배열 저장

ppp5500 2023. 12. 3. 18:44

기본 사항: State에 배열을 저장할 땐 불변한 것으로 취급해야 한다.(수정할 수 없다.)

 

따라서 배열을 수정하고 싶을 땐 기존의 배열 내용을 수정하는 것이 아니라 새로 생성해야 한다.

 

  피해야할 방법 권장되는 방법
추가 push, unshift concat, [...array]
삭제 pop, shift, splice filter, slice
교체 splice, arr[i] = .... map
정렬 reverse, sort copy the array first

 

배열에 추가하기

import { useState } from 'react';

let nextId = 0;

export default function List() {
  const [name, setName] = useState('');
  const [artists, setArtists] = useState([]);

  return (
    <>
      <h1>Inspiring sculptors:</h1>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
      />
      /* push 사용
      <button onClick={() => {
        artists.push({
          id: nextId++,
          name: name,
        });
      }}>Add</button>
      */
      
      // ...list를 사용 해서 배열 확장
      <button onClick={() => {
        setArtists([
          ...artists,
          { id: nextId++, name: name }
        ]);
      }}>Add</button>
   
      <ul>
        {artists.map(artist => (
          <li key={artist.id}>{artist.name}</li>
        ))}
      </ul>
    </>
  );
}

 

 

참고: https://react.dev/learn/updating-arrays-in-state