생명주기 함수 사용하기 (5)

DONI·2023년 2월 8일
0

React

목록 보기
8/8
post-thumbnail

🏹 shouldComponentUpdate( ) 함수

부모 컴포넌트로부터 새로운 props를 전달받거나
state가 변경되었을 때 실행되는 함수


🚩 소스코드 ( App.js )

App.js 파일에서 LifecycleEx를 import하는 부분을 다음와 같이 수정한다.

import LifecycleEx from './R008_LifecycleEx';

🚩 소스코드 ( R008_LifecycleEx.js )

src 폴더에 R008_LifecycleEx.js 파일 생성 후 다음과 같이 입력한다.

import React, { Component } from 'react';

class R008_LifecycleEx extends Component {
  static getDerivedStateFromProps(props, state) {
    console.log('2. getDerivedStateFromProps Call : ' + props.prop_value);
    return {tmp_state : props.prop_value};
  }

  constructor(props) {
    super(props);
    this.state = {};
    console.log('1. constructor Call');
  }

  componentDidMount() {
    console.log('4. componentDidMount Call');
    console.log('5. tmp_state : ' + this.state.tmp_state);
    this.setState({tmp_state2 : false});
    // tmp_state2라는 state 변수에 true라는 boolean 유형의 데이터를 세팅
    // setState() 함수 : 변수의 선언과 초기화를 동시에 실행
  }

  // state의 변경이 발생했기 때문에 변경 단계의 생명주기 함수 실행
  shouldComponentUpdate(props, state) {
    console.log('6. shouldComponentUpdate Call');
    console.log('7. tmp_state2 = ' + state.tmp_state2);
    return state.tmp_state2;
    // shouldComponentUpdate()는 boolean 유형의 데이터를 반환
    // 만약 return 값이 true일 경우 render() 함수를 한 번 더 호출
  }

  render() {
    console.log('3. render Call');
    return (
      <h2>[ THIS IS SHOULDCOMPONENTUPDATE FUCNTION ]</h2>
    )
  }
}

export default R008_LifecycleEx;

🔍 실행 결과

profile
틀린 내용이 있다면 댓글 또는 이메일로 알려주세요 ❤ꔛ❜

0개의 댓글