본문 바로가기
React

[리액트] 클래스형 컴포넌트 라이프사이클 메서드 componentDidUpdate 예제

by 메이플 🍁 2022. 8. 9.

componentDidUpdate

문법

componentDidUpdate(prevProps, prevState) { // 업데이트 되기 이전의 Props, State 값을 받아옴
  // 업데이트 된 값과, 업데이트 되기 이전의 값을 직접 비교해서, 함수를 실행시킴
  // 모든 props, state 값중 하나라도 변경사항이 있을 경우 실행할 코드를 이곳에 넣는다
  if (this.props.num !== prevProps.num) {
    // 특정 값이 업데이트 되었을 경우 실행할 코드를 이곳에 넣는다
    // num 이 업데이트되었을 때 실행할 코드
  }
}

예제

import React, { Component } from 'react';

class Comp extends Component {
  constructor(props) {
    super(props);
    this.countUp = this.countUp.bind(this);
    this.state = {
      num: 0,
      str: '안녕',
    }
  }
  
  // countUp이라는 함수가 실행되면 num의 값이 변경되므로 아래에 있는 componentDidUpdate 메서드가 실행된다
  countUp() {
    this.setState({
      num: this.state.num + 1
    });
  };

  componentDidUpdate(prevProps, prevState) {
    if (this.state.num !== prevState.num) {
      // num이 업데이트되었을 때 실행할 코드
      this.setState({
        str: '잘가'
      })
    }
  }
  
  render() {
    return (
      <div>
        <h1>{this.state.num}</h1>
        <button onClick={this.countUp}>카운트업!</button>
        // 버튼을 클릭할 경우 str의 데이터가 '잘가'로 변경된다
        <h1>{this.state.str}</h1>
      </div>
    );
  }
}

export default Comp;

댓글