프론트엔드/React

리액트 배열에 데이터 추가하기

랼랼 2022. 5. 13. 22:00

배열에 데이터를 추가하려면 concat 함수를 사용하거나 spread 연산자를 사용할 수 있다.

다음은 동물 종류와 동물 울음소리를 지정한 배열입니다.

이를 state에 animals 라는 이름으로 저장하겠습니다.

//animals state, 동물과 울음소리가 들어있음
const [animals, setAnimals] = useState([
    {
        id : 1,
        animalType : '고양이',
        sound : '야옹'
    },
    {
        id : 2,
        animalType : '강아지',
        sound : '멍멍'
    },
    {
        id : 3,
        animalType : '닭',
        sound : '꼬꼬댁'

    }
]);

 

input을 이용하여 데이터를 추가하기 위해 다음과 같은 메서드를 선언하였습니다.

//animals state에 새롭개 생성된 animal 객체 추가
const onCreate=()=>{
    const animal ={
        //nextId는 ref를 이용하여 랜더링되어도 변하지 않음
        id:nextId.current,
        animalType,
        sound
    }
    //----animals에 animal을 추가하는 메서드----//;
    //id 증가
    nextId.current++;
};

 

여기서 animals에 animal 객체를 추가하는 방법을 살펴보겠습니다.

 

state에 선언된 배열에 데이터를 추가하는 방법은 크게 두가지로 나눌 수 있습니다.

 

1) spread 연산자 이용 : setter에 [...복사할배열, 복사한 배열에 추가할 객체]

//spread 연산자
setAnimals([...animals,animal]);

2) concat() 함수 이용 : 복사할 배열 . concat(추가할 객체)

//concat 메서드
setAnimals(animals.concat(animal));

 

결과

 

입력한 데이터가 animals에 추가됩니다.

 

반응형