[React] state

2021. 12. 4. 16:44React.js | Vue.js

반응형

리액트에서 state는 컴포넌트 내부에서 바뀔 수 있는 값을 의미한다.

props를 바꾸려면 부모 컴포너너트에서 바꾸어 주어야 한다.

예를 들어, App컴포넌트에서 MyComponent를 사용할때 props를 바꾸어 주어야 값이 변경 된다.

반면 MyComponent에서는 전달 받은 name값을 직접 바꿀수 없다.

리액트에서는 2가지 종류의 state가 있다.

1)클래스형 컴포넌트가 지닌 state

2)함수형 컴포넌트가에서의 useState 라는 함수를 통해 사용하는 state

 

1) 클래스형 컴포넌트의 state

src디렉토리(폴더)에 counter.js 파일을 생성해 보자.

import { Component } from "react";

class Counter extends Component {
  constructor(props) {
    super(props);
    // state의 초깃값 설정하기
    this.state = {
      number: 0,
    };
  }
  render() {
    const { number } = this.state; // state를 조회할 때는 this.state로 조회한다.
    const style = {
      textAlign: "center",
    };
    return (
      <div style={style}>
        <h1>{number}</h1>
        <button
          onClick={() => {
            this.setState({ number: number + 1 });
          }}
        >
          +1버튼
        </button>
      </div>
    );
  }
}

export default Counter;

위 코드 실행 화면

이제 위의 코드를 해석해 보자

constructor(props) {
    super(props);
    this.state = {
      number: 0,
    };
  }

컴포넌트의 생성자 메서드이다.

클래스형 컴포넌트에서 constructor를 작성 할 때는 반드시 ❗️super(props)❗️를 호출해 주어야 한다.

이 함수가 호출 되면 현재 클래스형 컴포넌트가 상속 받고 있는 리액트의 Component클래스가 지닌 생성자 함수를 호출해 준다.

이번엔 render() 함수 안에 코드를 보자.

render() {
    const { number } = this.state; // state를 조회할 때는 this.state로 조회한다.
    const style = {
      textAlign: "center",
    };
    return (
      <div style={style}>
        <h1>{number}</h1>
        <button
          onClick={() => {
            this.setState({ number: number + 1 });
          }}
        >
          +1버튼
        </button>
      </div>
    );
  }

render 함수에서 현재 state를 조회할 때는 this.state를 조회하면 된다.

그리고 버튼이 클릭 되었을 때, 이벤트 함수를 설정해 두었다.

이벤트로 설정할 함수를 넣어 줄 때는 화살표 함수 문법을 사용하여 넣어 주어야 한다.

this.setState라는 함수는 state값을 바꿀 수 있게 해준다.

 

1-1) state를 constructor에서 꺼내기

state의 초깃값을 지정하기 위해 constructor 메서드를 선언해 주었다.

또 다른 방식으로도 state의 초깃값을 지정해 줄 수 있다.

 constructor(props) {
    super(props);
    this.state = {
      number: 0,
      fixedNumber: 0,
    };
  }
render(){...}

  /////////////////
  위에는 기존 코드이고,
  아래와 같이 코드를 수정해도 같은 결과값을 얻는다.
  /////////////////

state = {
    number: 0,
    fixedNumber: 0,
  };
render(){...}

이렇게 하면 constructor 메서드를 선언하지 않고도 state 초깃값을 설정할 수 있다.

 

 

2) 함수형 컴포넌트에서 useState 사용하기

아래 코드는 배열 비구조화 할당 문법이다.

const arr = [1,2];
const [one, two] = arr;

console.log(one) // 1
console.log(two) // 2

위 코드를 보고 나면, useState 사용 방법에 대해 좀 더 쉽게 이해 할 수 있을거다.

import { useState } from "react";

const Say = () => {
  const [msg, setMsg] = useState("");
  const onClickEnter = () => setMsg("안녕하세요!");

  const onClickLeave = () => setMsg("안녕히 가세요!");

  return (
    <div>
      <button onClick={onClickEnter}>입장</button>
      <button onClick={onClickLeave}>퇴장</button>
      <h1>{msg}</h1>
    </div>
  );
};

export default Say;

실행 뷰

 

 

⚠️ state를 사용할 때 주의 사항 !

클래스형 컴포넌트든 함수형 컴포넌트든 state를 사용할 때는 주의해야 할 사항이 있다.

state값을 바꾸어야 할 때는 setState 혹은 useState를 통해 전달 받은 세터 함수를 사용해야 한다.

 

반응형

'React.js | Vue.js' 카테고리의 다른 글

[Vue] ref  (0) 2022.08.31
[React] 이벤트 사용할때 주의 사항  (0) 2021.12.07
[React] props  (0) 2021.12.03
[React] 클래스형 컴포넌트  (0) 2021.12.03
[React] JSX 문법의 몇 가지 규칙  (0) 2021.12.03