본문 바로가기
2222
Stack & Tool/React

react.js로 영화 웹 서비스 만들기 -4 [동적data를 위한 class컴포넌트, state사용]

by PARK TAE JOON 2021. 7. 4.

이제 api는 지우고 동적으로 data를 변화시켜본다.

react에서 동적으로 data를 다루기 위해서는 먼저 function 컴포넌트가 아니라 class 컴포넌트를 사용한다.
그리고 state안에 변화시킬 값을 넣고 setState를 사용하면 react는 setState 부분이 작동할 때마다 render 함수 부분을 refresh 해준다.
하나의 공식이라고 생각하자.

this.setState({count : this.state.count += 1}) 이렇게 매번 this.state를 호출하는 것은 성능에 좋지 않다.
react는 이것에 대한 훌륭한 해결책을 제공해주는데 this.setState(current => {(count : current.count += 1 )} 이렇게 가능하다.
외우자. 유의해야 할 점은 괄호의 위치다.

import React from 'react';
import PropTypes from "prop-types";

class App extends React.Component { // react.component는 많은 것을 가지고 있지만 우리는 state를 쓸 것이다.
  state = {
    count : 0
  };
  add = () => {
    this.setState({count :this.state.count += 1}); // this를 앞에 붙여주는 것을 까먹지 말자.
  }
  minus = () => {
    this.setState({count : this.state.count -= 1});
  }
  render() { // function 컴포넌트는 return으로 시작했지만 class컴포넌트는 react.component안에 있는 render메소드를 호출해서 사용.
    return (
      <div>
        <h1>the number is : {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    )
  }
}

export default App;

Life cycle method

React.Component는 render말고 더 많은 걸 가지고 있다. 이것들은 life cycle method를 가진다. 컴포넌트를 생성하고 없애는 방법들이다.
component가 생성될 때 render 전에 호출되는 몇가지 function이 더 있다. 그 후에 호출되는 함수들도 있다.
update될 때 호출되는 또 함수들도 있다.
다 살펴보지는 않을 것이다. 필요한 것만 알아볼 것이다.

mounting

태어나는 것과 같다.

  • constructor
    호출되는 function이 하나 있는 constructor 이다. (constructor는 js에서 온 것 class를 만들 때 호출되는 것.)
    예시를 보기 위해서 아래와 같은 코드를 보았다.
  • class App extends React.Component { // react.component는 많은 것을 가지고 있지만 우리는 state를 쓸 것이다. constructor(props) { super(props) console.log("hello"); } ... render() { console.log("render");
  • componentDidMount()
    첫 렌더링이 다 완료됬을 때 (다 태어났을 때)

updating

일반적인 업데이트(내가 만든코드에서 add나 minus를 누른것.)
즉, setState를 호출할 때마다 발생.

setState가 호출되고나면 순서대로 실행된다.

  • static getDerivedStateFromProps() 건너 뛴다.
  • shouldComponentUpdate() 건너 뛰는데 이건 업데이트를 할지 말지 결정하는 것에 대한 것.
  • render()
  • getSnapshotBeforeUpdate() 사용해본적 없다한다.
  • componentDidUpdate

unmounting

컴포넌트가 죽는 것. 페이지가 바뀔 때를 의미. 다양한 방법이 있다.

import React from 'react';
import PropTypes from "prop-types";

// 3.0 state
// class 컴포넌트가 가진 state(동적으로 데이터 변화) 를 사용하기 위해서 class 컴포넌트를 사용한다.
// function 컴포넌트와 차이점이다.

// 3.1 state
// state를 직접 변경하지 말라고 console창에 뜬다.
// setState를 사용하라고 하는데 react는 setState를 만나면 자동으로 set한 뒤에 refresh를 해줘서 새로고침되면서 반영된다.

class App extends React.Component { // react.component는 많은 것을 가지고 있지만 우리는 state를 쓸 것이다.
  state = {
    count : 0
  };
  add = () => {
    this.setState(current => ({count : current.count += 1}))
  }
  minus = () => {
    this.setState(current => ({count : current.count -= 1}))
  }
  componentDidMount() { // render 된 후 
    console.log("component rendered")
  }
  componentDidUpdate() { // update 된 후
    console.log("i just updated")
  }
  componentWillUnmount() {
    console.log("good bye")
  }

  render() { // function 컴포넌트는 return으로 시작했지만 class컴포넌트는 react.component안에 있는 render메소드를 호출해서 사용.
    // 중요 : react는 class 컴포넌트의 render 메소드를 자동으로 실행한다. // class이기 때문에 this.state.count
    console.log("rendering")
    return (
      <div>
        <h1>the number is : {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    )
  }
}

export default App;

로딩과 완료 구현

컴포넌트가 완료됬을 때 나타나는 화면을 연습해본다.

class App extends React.Component {
    state = {
        isLoading = True
    }
    componentDidMount() { // 마운트가 끝났을 때.(한번 render됬을 때)
        setTimeout( () > {
            this.setState({isLoading:false})
        }, 3000);
    }

render() {
    const {isLoading} = this.state; // this.state는 {isLoading : true} 를 담고 있다. const {} 이렇게 받음으로서 true 그대로 받는다.
    return <div>
        {isLoading ? "Loading" : "we are ready"}
    </div>
}
}

댓글