[React] state 객체 안에 여러 값이 있을 때&constructor에서 state 꺼내기

겨레·2024년 11월 13일

[React] 리액트 스터디

목록 보기
21/95

👉 state 객체 안에 여러 값이 있을 때

state 객체 안에는 여러 값이 있을 수 있다.

  • Counter.jsx
import React, { Component } from 'react';
 
class Counter extends Component {
  constructor(props) {
    super(props);
    // state 초깃값 설정
    this.state = {
      number: 0,
      fixedNumber: 0, // 추가된 state 객체!!!
    };
  }
  render() {
    // 여기에도 새로 작성한 객체 추가!!!!!
    const { number, fixedNumber } = this.state;
    return (
      <div>
        <h1>{number}</h1>
        <h2>바뀌지 않는 값: {fixedNumber}</h2>
        <button
          onClick={() => {
            this.setState({ number: number + 1 });
          }}
        >
          +1
        </button>
      </div>
    );
  }
}
 
export default Counter;

버튼이 클릭될 때 fixedNumber 값은 그대로 두고 number 값만 바꿈. 그렇다고 해서 this.setState 함수를 사용할 때 인자로 전달되는 객체 내부에 fixedNumber를 넣어 주지는 않았음. this.setState 함수는 인자로 전달된 객체 안에 들어 있는 값만 바꿔줌. 그 결과, 맨 위에 있는 숫자만 업데이트되고 하단의 숫자는 고정됨.



👉 constructor에서 state 꺼내기

state의 초깃값을 지정하기 위해 constructor 메서드를 선언해 줌. 또 다른 방식으로도 state의 초깃값을 지정할 수 있음. 그럼 constructor 메서드를 선언하지 않고도 state 초깃값을 설정할 수 있게됨.

mport React, { Component } from 'react';
 
class Counter extends Component {
  state = {
    number: 0,
    fixedNumber: 0
  };
  render() {
    const { number, fixedNumber } = this.state; // state를 조회할 때는 this.state로 조회
    return (...);
  }
}
 
export default Counter;
profile
호떡 신문지에서 개발자로 환생

0개의 댓글