뭐든 즐기면서 ;)

React 생명주기 / React 클래스 컴포넌트 생명주기1 (Mount) 본문

FRONT/React

React 생명주기 / React 클래스 컴포넌트 생명주기1 (Mount)

Tada.*+ 2021. 11. 5. 19:55
728x90

- will 접두사가 붙은 함수는 어떤 작업을 처리하기 직전에 호출되는 함수입니다.

- did 접두사가 붙은 함수는 어떤 작업을 처리한 후에 호출되는 함수입니다.

 

※ Mount : DOM 객체가 생성되고, 브라우저에 나타나는 것을 의미합니다.

이 때 호출되는 함수 순서는 아래와 같습니다.

- constructor : 컴포넌트 클래스의 생성자 함수로 컴포넌트 생성을 할 때 처음으로 호출되는 함수입니다.

  state의 초기값을 지정하는 영역입니다.

- getDerivedStateFromProps : props와 state값을 동기화할 때 사용하는 함수입니다.

  • props로 받아온 값을 state에 넘겨줄 때 사용.
  • 컴포넌트가 갱신될 때(=state값이 변경될 때)에도 호출됩니다.
  • 리액트 16.3 버전이후 만들어진 함수.
  • constructor 함수 내에 this.state 선언을 해주어야 한다. 그렇지 않으면 warning 발생.

- render : 컴포넌트의 모양새(html)를 정의하고, 리액트 요소(element)를 반환하는 함수입니다.

- componentDidMount : 컴포넌트(출력물)가 DOM에 렌더링된 후에 실행되는 함수입니다.

  * 하나의 컴포넌트가 여러 번 사용될 경우, constructor, getDerivedStateFromProps, render 함수가

여러 번 불려온 후 맨 마지막에 호출이 된다.(무슨 뜻인지는 아래 첨부할 예정.)

class Welcome extends React.Component {
    constructor(props) {
        super(props);
        // getDerivedStateFromProps 오류가 발생하지 않기 위해서 this.state 선언
        this.state = {
            name : 'HyePark'
        }
        console.log('constructor 호출');
    }

    static getDerivedStateFromProps(nexProps, prevState) {
        console.log("getDerivedStateFromProps 호출");
        return null;
    }

    render() {
        console.log("render 호출");
        return <div>Hello, {this.state.name}</div>;
    }

    componentDidMount() {
        console.log("componentDidMount 호출");
    }
} // end of Welcome component class

function Welcomes() {
    return (
        <div>
            <Welcome name="q"/>
            <Welcome name="a"/>
        </div>
    );
}

ReactDOM.render(
    <Welcomes/>,
    document.getElementById('root')
);

화면 결과물
콘솔창 결과

* 콘솔창결과를 보면 componentDidMount는 모든Welcome component가 DOM에 렌더링된 후 한 번에 모두 실행된다.

* 위에서 getDerivedStateFromProps함수의 경우 컴포넌트가 업데이트될 때에도 호출이 된다고 설명했습니다. 아래 이미지와 함께 설명하겠습니다.

- 확인 방법

  1. google developer 툴 중 React개발에 도움이 되는 확장 기능 중 하나를 사용(React Developer Tools)
  2. state값 변경

Welcome 컴포넌트의 state.name 값을 'HyePark'에서 'HyePark1'로 변경

 

   3. 결과 확인

 


※ getDerivedStateFromProps 사용방법

- getDerivedStateFromProps의 인자 값 확인

class Welcome extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name : 'HyePark'
        }
    }

    static getDerivedStateFromProps(nexProps, prevState) {
        console.log("getDerivedStateFromProps 호출");
        console.log('nexProps', nexProps);
        console.log('prevState', prevState);
        return null;
    }

    render() {
        return <div>Hello, {this.state.name}</div>;
    }
}

function Welcomes() {
    return (
        <div>
            <Welcome name="q"/>
            <Welcome name="a"/>
        </div>
    );
}

ReactDOM.render(
    <Welcomes/>,
    document.getElementById('root')
);

 

- getDerivedStateFromProps함수를 사용하여 state값을 변경하였을 때

static getDerivedStateFromProps(nexProps, prevState) {
        console.log("getDerivedStateFromProps 호출");
        console.log('nexProps', nexProps);
        console.log('prevState', prevState);
        prevState.name = nexProps.name;
        console.log('nexProps', nexProps);
        console.log('prevState', prevState);
        
        // state 값 변경이 필요 없을 경우 null을 반환
        // return null;
    }

중간에 warning은 return null의 주석을 풀어주면 됨.(오류 해결을 위해서는 return값이 필요함.)

 

이전 글 : 2021.11.04 - [UI/React] - React state와 props 차이점 / React props와 state 차이점

 

React state와 props 차이점 / React props와 state 차이점

State (동적인 데이터를 다룸) 1. state는 컴포넌트에 의해 제어됩니다. 2. 사용자가 알 필요 없는 데이터를 내부에 은닉하여 사용하기 위해 state가 존재합니다.(캡슐화) 2-1. 컴포넌트 내부에서 선언

tadaiswhatever.tistory.com

다음 글 : 2021.11.06 - [UI/React] - React 생명주기 / React 클래스 컴포넌트 생명주기2 (Update & Unmount)

 

React 생명주기 / React 클래스 컴포넌트 생명주기2 (Update & Unmount)

※ Update : 컴포넌트가 업데이트될 때 실행되는 함수들. - 컴포넌트가 업데이트되는 경우 1. pops값 변경 2. state값 변경 3. 부모 컴포넌트가 리렌더링될 때 4. this.forceUpdate로 강제로 리렌더링 시킬

tadaiswhatever.tistory.com

 

728x90
Comments