[React] 클래스형 라이프사이클

grace·2023년 1월 19일

React

목록 보기
3/10
post-thumbnail

클래스 컴포넌트 라이프 사이클

[Mounting : 컴포넌트가 시작될 때 ]

constructor 는 첫번째로 실행되는 lifecycle 함수로써 컴포넌트가 실행될 때 먼저 호출하고 들어가게 된다. 앱이 실행되자 마다 해줘야 하는 작업들을 넣어주면 좋다.

getDerivedStateFromProps 는 간단히 state 와 props를 동기화시켜주는 함수

render 는 UI 를 그려주는 함수

componentDidMount 는 UI 세팅이 완료되면 알려준다.

눈으로 보면 뭔소리인지 모르겠으니…콘솔..콘솔을 보자…

import React, { Component } from "react";

export default class AppClass extends Component {
  //constructor 생성자:컴포넌트가 실행되자 마자 호출이 되는 함수로 클래스의 기본함수이다.
  //즉,state 만들어주고~
  constructor(props) {
    super(props);
    //state 라는 object를 만들고 그 안에 내가 원하는 state를 다 넣으면 된다.
    this.state = {
      counter: 0,
      num: 1,
      value: 0,
    };
    console.log("constructor");
  }
  increase = () => {
    this.setState({
      counter: this.state.counter + 1,
      value: this.state.value + 1,
    });
  };
  componentDidMount() {
    //API calll
    console.log("componentDidMount");
  }
  render() {
    //render는 UI 를 그려주는 것
    console.log("render");
    return (
      <>
        <div>
          {/* this.state를 매번 써야하는 불편함이 있다. */}
          <div>state{this.state.counter}</div>
          <button onClick={this.increase}>클릭</button>
        </div>
      </>
    );
  }
}

짜-짠!


[Updating: stater가 업데이트 되고 UI 업데이트 될 때]

getDerivedStateFromProps 는 간단히 state 와 props를 동기화시켜주는 함수

sholudComponentUpdate 는 컴포넌트가 render를 할지말지 결정하는 함수

render 는 UI 를 그려주는 함수

componentDidUpdate 는 state가 업데이트가 됐는지 알려주는 함수

import React, { Component } from "react";

export default class AppClass extends Component {
  //constructor 생성자:컴포넌트가 실행되자 마자 호출이 되는 함수로 클래스의 기본함수이다.
  //즉,state 만들어주고~
  constructor(props) {
    super(props);
    //state 라는 object를 만들고 그 안에 내가 원하는 state를 다 넣으면 된다.
    this.state = {
      counter: 0,
      num: 1,
      value: 0,
    };
    console.log("constructor");
  }
  increase = () => {
    this.setState({
      counter: this.state.counter + 1,
      value: this.state.value + 1,
    });
    console.log("increase function", this.state);
  };
  componentDidMount() {
    //API calll
    console.log("componentDidMount");
  }

  componentDidUpdate() {
    console.log("componentDidUpdate", this.state);
  }

  render() {
    //render는 UI 를 그려주는 것
    console.log("render");
    return (
      <>
        <div>
          {/* this.state를 매번 써야하는 불편함이 있다. */}
          <div>state{this.state.counter}</div>
          <button onClick={this.increase}>클릭</button>
        </div>
      </>
    );
  }
}


[Unmounting:컴포넌트가 종료될 때]

.
.
.

끝!

profile
미래의 개발자!

0개의 댓글