TIL - React Class state ( React - 4 )

rain98·2021년 6월 5일
0

TIL

목록 보기
30/32
post-thumbnail

State란 무엇일까?

state의 어원은 상태라는 뜻이다.
단어의 뜻을 리액트로 해석을 해보면 컴포넌트 내부에서 가지고 있는 컴포넌트의 상태값이다.

어디서 쓰일까?

항상 우리가 컴포넌트를 만들 때 동적인 부분이 하나도 없을까?
아니다 오히려 값이 바뀌는 일이 많다고 할 수 있다.
컴포넌트에서 보여줘야 하는 내용이 사용자 인터랙션에 따라 바뀌어야 할때 유용하게 사용 하는것이 state이다.

state 는 컴포넌트 내부에서 선언하며 내부에서 값을 변경 할 수 있다.


카운터 컴포넌트를 만들어보자

카운터 컴포넌트를 예시로 두고 설명하고자 한다.

import React from 'react';

class Counter extends React.Component {
  constructor() {
    super();
    this.state = {
      number: 0
    }
  }

  handleIncrease = () => {
    this.setState({
      number: this.state.number + 1
    });
  }

  handleDecrease = () => {
    this.setState({
      number: this.state.number - 1
    });
  }

  render() {
    return (
      <div>
        <h1>카운터</h1>
        <div>: {this.state.number}</div>
        <button onClick={this.handleIncrease}>+</button>
        <button onClick={this.handleDecrease}>-</button>
      </div>
    );
  }
}

export default Counter;

1. State 정의

Class형 state를 사용 할 때 이런 문법을 사용하면된다

constructor() {
   super();
   this.state = {
     key:value // <-키와 밸류 형태로 저장
   }
 }
render() { 
  ...
}
  • state를 설정할 때는 화면에 보이듯이 constructor 함수를 작성하여 설정한다.

  • 클래스형 컴포넌트 안에는 필수적으로 render 함수 가 필요하고 화면에 나타내고 싶은 JSX 요소가 return 문 안에 들어있다.

  • constructor 함수는 컴포넌트 선언문(class State extends Component)과 render 함수 사이에 작성한다.

  • 그리고 constructor 메소드 안에는 super()를 호출한다.

  • 그 다음에는 this.state 값에 컴포넌트의 초기 상태값을 설정 한다.

State 객체

this.state = {
      number: 0 // <-키와 밸류 형태로 저장
    }

객체 안의 key 이름은 원하는대로 설정할 수 있다.
컴포넌트의 state는 객체 형태로 정의한다.

위에 카운터 컴포넌트의 예시를 들어 설명을 하자면

constructor() {
    super();
    this.state = {
      number: 0 // <-키와 밸류 형태로 저장
    }
  }

number를 0으로 저장을 해두고 state의 저장된 number를 유동적으로 사용 한다는 소리다.


여기서 super()을 호출해주는 이유?

super() 를 호출해 주는 이유는, constructor 안에서 this 를 사용하기 위해서 이다.


2.setState

리액트에서는 state에 저장되어있는 값의 원본을 변경 시키는걸 막고 있다. state의 값을 변경 시키기 위해 setState를 통해 변경을 해야한다.

메소드 작성

handleIncrease = () => {
    this.setState({
      number: this.state.number + 1
    });
  }

  handleDecrease = () => {
    this.setState({
      number: this.state.number - 1
    });
  }

setState를 통해 state의 number의 숫자를 변경 할 수 있다.
this.state.number는 state의 number의값인 0을 가리킨다.

handleIncrease함수는 number에 1을 증가 시키는 함수
handleDecrease함수는 number에 1을 감소 시키는 함수

3.이벤트 설정

render() {
    return (
      <div>
        <h1>카운터</h1>
        <div>: {this.state.number}</div>
        <button onClick={this.handleIncrease}>+</button>
        <button onClick={this.handleDecrease}>-</button>
      </div>
    );
  }

값: {this.state.number} 여기서 방금 전에 말했듯 this.state.number는 state의 number의값인 0을 가리킨다.
값: 0 으로 나온다.

<button> 요소에서 onClick이벤트를 통해 버튼이 클릭되면 만들어두었던 함수가 각각 호출되도록 설정한다.

+버튼을 클릭하면 this.handleIncrease함수가 실행하여 state의 number의 값을 1추가 한다.

반대로 -버튼을 클릭하면 this.handleDecrease함수가 실행하여 state의 number의 값을 1감소 한다.

profile
헷갈리거나 기억에 남기고 싶은것을 기록합니다.

0개의 댓글