useState
useState 함수를 사용한 state 관리
함수형 컴포넌트에서는 state를 직접 생성하지 않고React.useState 함수를 사용하여 생성한다.
state 선언
생성 구문은 다음과 같다.
const [name, setName] = React.useState("피카츄");위 구문은 다음 의미를 가진다.
name이라는 이름의 상태 변수를 만든다.
setName 함수를 통해 name의 변경을 처리한다.
name의 초기값은
"피카츄"로 한다.
state 출력
state의 출력은 함수에서 반환되는 JSX 구문에서 한다. 클래스의 render 함수에서 하듯이 표현식 {} 을 사용하여 생성된 변수를 출력한다.
function MainComponent(){
const [name, setName] = React.useState("피카츄");
return (
<>
<h1>Name is {name}</h1>
</>
);
}state 여러 개 선언
여러 개의 데이터를 state로 선언할 경우 React.useState 함수를 데이터마다 각각 사용한다.
function MainComponent(){
const [name, setName] = React.useState("피카츄");
const [type, setType] = React.useState("전기");
return (
<>
<h1>이름 : {name}</h1>
<h1>속성 : {type}</h1>
</>
);
}state에 배열 선언
function MainComponent(){
const [numbers, setNumbers] = React.useState([10, 20, 30]);
const view = numbers.map(number=><li>{number}</li>);
return (
<>
<h1>숫자 목록</h1>
<ul>{view}</ul>
</>
);
}state에 객체 선언
function MainComponent(){
const [monster, setMonster] = React.useState({
no : 1, name : "이상해씨", type:"풀"
});
return (
<>
<h1>번호 : {monster.no}</h1>
<h1>이름 : {monster.name}</h1>
<h1>유형 : {monster.type}</h1>
</>
);
}Last updated