Written by
Lee Jongseo
on
on
React - state 변경하기
React의 State
State는 리엑트 컴포넌트안에서 정의되고 변경 가능한 데이터다.
기본적으로 클래스형 컴포넌트에서 사용하며 함수형 컴포넌트에서는 useState 훅을 이용해 사용할 수 있다.
State값이 변경하여 업데이트가 발생하면 리렌더링이 이루어진다.
State 정의
클래스형 컴포넌트에서 State는 constructor 안에서 정의하거나 클래스 내부 프로퍼티로 정의할 수 있다.
constructor 이용
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
stateKey1: stateValue1,
stateKey2: stateValue2,
}
}
//...
}
Class property 이용
import React, { Component } from 'react';
class MyComponent extends Component {
// this가 필요없다.
state = {
stateKey1: stateValue1,
stateKey2: stateValue2,
}
//...
}
state 변경
state가 변경한다는 것은 in-place 변경이 아니라 기본적으로 새로운 state객체가 할당되고 새로운 state객체를 이용하여 리렌더링을 한다는 것을 의미한다.
state내용을 변경하기 위해서는 state객체에 직접 접근해 새로운 값을 재할당을 하는 것이 아니라 setState()함수를 이용하여 state내용을 변경한다.
//...
state = {
message: "Ready"
}
render() {
const {message} = this.state
return (
<div>
<h1>{message}
<button onClick={() => {
this.setState({
message: "Go"
})
}}>Go</button>
</div>
)
}
setState() 함수는 이벤트 헨들러 내에서 비동기적이다. state를 비동기적으로 업데이트한다.
비동기적으로 업데이트한다는 것은 setState함수 코드가 실행되고 그 즉시 state를 업데이트 하지 않는다는 뜻이다.
이전 state와 비교해서 값을 업데이트하기 위해서는 setState인자에 함수를 넣어줘야 한다.
// ...
state = {
count = 0,
}
render() {
const {count} = this.state
return (
<div>
<h1>{count}</h1>
<button onClick={() => {
this.setState((prevState => {
count: prevState.count + 1
}))
}}>증가</button>
</div>
)
}
<button>