우사미 코딩

[React] state - 배열 초기화, 새로운 요소 추가하기 본문

React

[React] state - 배열 초기화, 새로운 요소 추가하기

맑은 눈의 우사미 2023. 6. 23. 14:24
반응형
import { useState } from "react";

function getRandomAnimal(){
    const animals = ['bird','cat','cow','dog','gator', 'horse']; 
    return animals[Math.floor(Math.random() * animals.length)]; 
}

function App(){    
    const[animals, setAnimals] = useState([]);
    const handleClick = () =>{
        setAnimals([...animals, getRandomAnimal()]);
        console.log(animals);
    }
    return (
        <div>
            <button onClick={handleClick}>Add animal</button>
            <div>{animals}</div>
        </div>
    );
}
export default App;

line 9 : animals라는 배열을 만들고 setter를 설정했습니당. 초기값은 빈 배열

line 11 : 우리는 state를 변경할때 무.조.건. setter함수를 사용하기로 했어요.

 

setAnimals([...animals, getRandomAnimal())은 무슨뜻이냐?

기존 animals 배열의 끝에 getRandomAnimal() 리턴값을 추가하라는 것임

 

반응형
Comments