본문 바로가기

React

React 생명주기 함수 '변경'

728x90

React 생명주기 함수 '변경'과정에 속하는 함수는 shouldComponentUpdate()로 여기서 '변경'이란 props나 state의 변경을 말한다. shouldComponentUpdate() 함수의 실행을 확인해 보기 위해 다음과 같이 코드를 수정해 보자.

import React, {Component} from 'react';

class Component1 extends Component{
    static getDerivedStateFromProps(props, state){
         console.log('2번'+props.value+'실행');
         return {sValue:props.value, eValue:'중간 두번째'};
    }
    constructor(props){
        super(props);
        this.state = {};
        console.log('1번 실행');
    }
    componentDidMount(){
        console.log('4번 state : '+this.state.sValue);
        console.log('5번 state : '+this.state.eValue);
        this.setState({tValue:true});
    }
    shouldComponentUpdate(props, state){
        console.log('6번 실행'+ state.tValue);
        return state.tValue
    }
    render(){
        console.log('3번 실행');
        return(
            <h2>[component1 입니다]</h2>
        )
    }
}

export default Component1;

함수가 많아져 실행 번호를 추가해 주었고, componentDidMount() 함수 내에서 tValue = true 값을 추가해 state에 변경을 발생시켜 shouldComponentUpdate를 실행시키고 return 값이 true일 때 render() 함수가 한번 더 호출된다.

실행 결과 5번까지 정상적으로 실행되고 componentDidMount()에서 state변경이 발생했으므로 component가 재랜더링 되게 되는데 이때 부모 컴포넌트가 자식 component에서 새로운 props를 전달하기 때문에 getDerivedStateFromProps() 함수가 실행이 되고, 다음 state값의 변경이 이루어졌으니 shouldComponentUpdate() 함수가 실행, 마지막으로 render() 함수가 실행된다.

728x90

'React' 카테고리의 다른 글

화살표 함수 사용하기  (0) 2024.04.12
React 전개 연산자  (0) 2024.04.12
React 생명주기 함수 '생성'  (0) 2024.03.28
React Component 사용하기  (0) 2024.03.27
React 메인 바꿔보기  (0) 2024.03.27