No.3 ReactJS로 영화 웹 서비스 만들기

Jetom·2021년 8월 10일
0

react

목록 보기
3/15
post-thumbnail

Class Components and State

props를 어떻게 활용하는지 전 글에서 알아봤으니 이제 만들었던 코드들은 지운 뒤, state에 대해 알아보자.(😢)

state는 동적 데이터와 함께 작업할 때 만들어진다. 동적 데이터는 변하는 데이터, 존재하지 않는 데이터, 생겨나고 사라지는 데이터 등등이라 할 수 있으며, 이 데이터들을 dynamic data(= 동적 데이터)라 한다.

이제 function component였던 component를 class component로 바꾸어준다(function이 들어가면 function component고 class로 만들면 class component다.)

//class component를 만들면 import에서 자동적으로 { Component }를 불러온다.
import React, { Component } from 'react';

//React.Component에 React를 생략해도 된다.
class App extends Component{
  render(){
    return <h1>class component😜</h1>
  }
}

class component는 function component와 달리 return을 가지고 있지 않다. 그 이유는 react component에서 extend from을 했기 때문에 render method를 가질 수 있어서이다.

function component는 말 그대로 function이고 뭔가를 return해야 화면에 보이게된다. 하지만 class component는 class인데, react component로 부터 확장되고 화면에 보이게된다.(그래서 class는 render method 안에 넣어야한다.)

class component를 언급하는 이유는 우리가 원하는 state 때문인데, state는 object이며 변하는 data이다. 이것에 대해 알아보려고 counter를 만드려한다. 아래 예제 코드처럼 만들어보자!

//React.Component에 React를 생략해도 된다.
class App extends Component{
  state = {
    {/* state는 바꿀 데이터를 넣는것!*/}
  	count: 0
  }
  
  render(){
    {/* class이기 때문에 아래와 같이 코드를 작성해야 동작한다.*/}
    return <h1>number is {this.state.count}</h1>
  }
}

state에 바꿀 데이터를 넣어줬는데, 이제 app에서 어떻게 data를 바꿔야할까?

//React.Component에 React를 생략해도 된다.
class App extends Component{
  state = {
  	count: 0
  }
  
  render(){
    {/* 버튼 두개를 추가한 뒤 add와 minus라고 지어준다. */}
    return <div>
      	<h1>number is {this.state.count}</h1>
      	<button>Add</button>
      	<button>Minus</button>
      </div>
  }
}

현재 JSX도 변경되지 않았고 html도 정상적이지만 차이점은 state가 class component에 있기 때문에 우리는 this.state를 해야한다. (이 작업은 component data를 바꾸기 위한것을 기억하자!)

//React.Component에 React를 생략해도 된다.
class App extends Component{
  state = {
  	count: 0
  }
  
  {/*javascript로 add와 minus function을 작성한다. */}
  add = () => {
    console.log('add');
  };
  minus = () => {
    console.log('minus');
  };
  

  render(){
    return <div>
      	<h1>number is {this.state.count}</h1>
       {/* react에서는 onClick이라는 prop을 호출한다. */}
      	<button onClick={this.add()}>Add</button>
      	<button onClick={this.minus()}>Minus</button>
      </div>
  }
}

add와 minus 버튼을 클릭하니 console에 찍히는 모습을 볼 수 있다.

state를 업데이트 하는건 다음 글에서 쓰겠당...
(class의 개념을 정확하게 알지 못하니.. javascript class를 공부해야해서.....😢)

profile
사람이 좋은 인간 리트리버 신혜리입니다🐶

0개의 댓글