주니어 기초 코딩공부/React 기초

생명주기 함수 componentDidMount, shouldComponentUpdate() 알아보기

jju_developer 2023. 4. 5. 20:08
728x90

안녕하세요 jju_developer입니다.

 

지난 시간의 노드 js에 이어서 4번째의 componentDidMount에 대해 알아보겠습니다.

 

노드JS 개념 이해하기 + 다운로드 (npm과 yarn이란?)

노드 JS란 무엇일까? 안녕하세요 jju_developer입니다. 오늘부터 대망의 react에 대해서 공부를 하게되었습니다! Node.js는 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임입니다. 말이 참 어렵죠? Java

jju240.tistory.com

 

 

2장 yarn css, 함수형, 클래스형 component 예제, 생명주기 함수 render() 사용하기

안녕하세요 jju_developer입니다. 이어서 리엑트 수업에서 배운 내용을 정리하여 공유드립니다. cd 001로 이동 다운로드 후, yarn start를 칩니다. * yarn start - 우리가 작성한 코드를 직접 확인해 볼 수 있

jju240.tistory.com


007 생명주기 함수 componentDidMount() 사용하기

componentDidMount

 

 

import React from 'react';
import './App.css';
import LifecycleEx from './R007_LifecycleEx'

function App() {
  return (
    <div>
      <h1>componentDidMount 쮸 Start React 200!</h1>
      <p>CSS 적용하기</p>
      <LifecycleEx
        prop_value = 'FromApp.js'
      />
    </div>
  );
}

-> App.js

 

import React, { Component } from 'react';

class R007_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);
  }

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

export default R007_LifecycleEx;

-> R007_LifecycleEx

 

지금 보려고 하는 부분이 바로 이 부분입니다.
  componentDidMount() {
    console.log('4. componentDidMount Call');
    console.log('5. tmp_state : '+this.state.tmp_state);
  }

콘솔에 어떻게 호출되는지 볼까요?

지난 시간에 어떻게 출력되는지 보았고

이번에는 4,5번이 출력되었습니다.


008 생명주기 함수 shouldComponentUpdate() 사용하기

shouldComponentUpdate() 함수는 component의 변경 과정에 속합니다.

 

여기서 변경이란 props나 state의 변경을 뜻합니다.
 R008_LifecycleEx.js 파일
• state의 변경이 발생하기 때문에 '변경' 단계의 생명주기 함수 shouldComponentUpdate()가 실행됩니다.
• ShouldComponentUpdate()는 boolean 유형의 데이터를 반환하는데, return 값이 true일 경우에 render() 함수를 한 번 더 호출합니다.

import React from 'react';
import './App.css';
import LifecycleEx from './R008_LifecycleEx'

function App() {
  return (
    <div>
      <h1>shouldComponentUpdate 쥬쥬 Start React 200!</h1>
      <p>CSS 적용하기</p>
      <LifecycleEx
        prop_value = 'FromApp.js'
      />
    </div>
  );
}

export default App;

 

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 : true});
  }

  shouldComponentUpdate(props, state) {
    console.log('6. shouldComponentUpdate Call / tmp_state2 = ' + state.tmp_state2);
    return state.tmp_state2
  }

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

export default R008_LifecycleEx;

이제 점점 길어지기 시작했네요 ㅎㅎ

  componentDidMount() {
 this.setState({tmp_state2 : true});

여기서 state를 tmp_State2 라는 것으로 변경을 시키는 것입니다.

이때에 shouldComponentUpdate

얘가 실행이 되어서 state에 들어있는 state2의 값을 출력시키는 것입니다!

여기서

 

sholdComponentUpdate가 리턴이 true면 render()를 한 번 더 실행한다고 했죠?

 

 

 

생성이 다 끝난 상태에서 porps 변경 또는 setState를 호출하면 shouldComponentUpdate가 돌고

그 결과가 true일 때 render가 돈다는 뜻입니다!!!!!!

 

그래서 이번 예제를 보면 render()가 하나가 더 돌아서 

render가 두 개인 것을 볼 수 있습니다.

 

오늘도 고생하셨습니다 😆

728x90