React : state 값 선언, 두가지 예시 constructor

🍒Jooooooo_eun🍒·2021년 12월 8일
0

React basic

목록 보기
3/16
post-thumbnail

react에서 state 값을 선언할때 두가지 예시로 선언이 가능하다.


방법 1. state = {key : value} 선언


class Component extends React.Component{
     state = {count : 0} //state 선언

      render() {
         return (
            <div>
              <h1>
                {this.props.message} massage 데이터 입니다.
              </h1>
              //state 사용
              <p>{this.state.count}</p> state 사용
            </div>
        )
     }
}

이 방법이 쉽지만 때론 다른 방법을 사용해야 하는 상황이 오기도 한다.




방법2. constructor(props) 사용

class Component extends React.Component{ 
      
      constructor(props) { // 생성자 함수 선언
        super(props); // 문법상 super(props)를 선언
        this.state = { count: 0 };  //state 선언
      }
     
      render() {
         return (
            <div>
              <h1>
                {this.props.message} massage 데이터 입니다.
              </h1>
              //state 사용
              <p>{this.state.count}</p> state 사용
            </div>
        )
     }
}

문법이 어렵다면 그냥 외우는걸 추천합니다!
기존 값을 넣어주는 state가 직관적이라 사용하기 편리해보이지만
때론 constructor을 사용할때도 있기때문에 두개 모두 알아두자!

profile
먹은만큼 성장하고 싶은 초보 개발자의 끄적끄적 개발메모장 ✍

0개의 댓글