본문 바로가기

React

React 생명주기 함수 '생성'

728x90

React에서 생명주기란, component의 생성, 변경, 소멸 과정을 뜻한다. 그중 render(), constructor(), getDerivedStateFormProps(), componentDidMount() 함수들은 '생성'에 속하며 사용방법은 다음과 같다.

 

1. render()

render()는 return 되는 html 형식의 코드를 화면에 그려주는 함수로 다음과 같이 사용할 수 있다.

import React, {Component} from 'react';

class Component1 extends Component{
    render(){
        return(
            <h2>[component1 입니다]</h2>
        )
    }
}

export default Component1;

위와 같이 적용하면 component1을 사용하는 곳에는 <h2>[component1입니다]<h2>가 출력될 것이다. 

 

2. constructor(props)

constructor(props)는 생명주기 함수 중 가장 먼저 실행되며, 처음 한 번만 호출된다.

보통 component 내부에서 사용되는 변수(state)를 선언하고 부모 객체에서 전달받은 변수(props)를 초기화할 때 사용하며 super() 함수는 가장 위에 호출해야 한다. 다음과 같이 코드를 작성하여 확인해 보자.

import React, {Component} from 'react';

class Component1 extends Component{
    constructor(props){
        super(props);
        this.state = {};
        console.log('먼저 실행');
    }
    render(){
        console.log('뒤에 실행');
        return(
            <h2>[component1 입니다]</h2>
        )
    }
}

export default Component1;

위처럼 코드를 작성 후 브라우저에서 F12버튼을 눌러 개발자도구를 연 후 콘솔창에 들어가 확인해 보면

cnostructor에 작성한 console.log가 먼저 실행되고 render에 작성한 console.log가 뒤에 실행되는 것을 확인할 수 있다.

 

3. static getDerivedStateFormProps(props, state)

getDerivedStateFromProps(props, state) 함수는 constructor() 함수 다음으로 실행되며 컴포넌트가 새로운 props를 받게 됐을 때 state를 변경해 준다. 사용방법은 다음과 같다.

import './App.css';
import Component1 from './component/Component1';

function App() {
  return (
    <div>
      <h1>안녕하세요.</h1>
      <p>메인페이지입니다.</p>
      <Component1 value = '중간'/>
    </div>
  );
}

export default App;

1) App.js의 Component에 value = '중간'이라는 변수를 설정해 주고

import React, {Component} from 'react';

class Component1 extends Component{
    static getDerivedStateFromProps(props, state){
         console.log(props.value+'실행');
         return {};
    }
    constructor(props){
        super(props);
        this.state = {};
        console.log('먼저 실행');
    }
    render(){
        console.log('뒤에 실행');
        return(
            <h2>[component1 입니다]</h2>
        )
    }
}

export default Component1;

2) 설정된 변수는 getDerivedStateFromProps의 props에 담겨있으므로 props.value로 값을 꺼내 쓰면 된다.

3) 실행 결과 App.js에 변수 설정한 '중간'을 getDerivedStateFromProps에서 사용한 것을 볼 수 있고, constructor 다음으로 실행된 것 또한 확인할 수 있다.

 

4. componentDidMount()

componentDidMount() 함수는 가장 마지막으로 실행되며 이벤트 처리, 초기화 등 화면이 모두 그려진 후 실행돼야 할 때 사용한다. 실행 순서는 다음과 같이 확인할 수 있다.

import React, {Component} from 'react';

class Component1 extends Component{
    static getDerivedStateFromProps(props, state){
         console.log(props.value+'실행');
         return {sValue:props.value, eValue:'중간 두번째'};
    }
    constructor(props){
        super(props);
        this.state = {};
        console.log('먼저 실행');
    }
    componentDidMount(){
        console.log('state : '+this.state.sValue);
        console.log('state : '+this.state.eValue);
    }
    render(){
        console.log('뒤에 실행');
        return(
            <h2>[component1 입니다]</h2>
        )
    }
}

export default Component1;

1)  getDerivedStateFromProps() 함수에서 return으로 변수와 변숫값을 지정해 준다.

2) componentDidMount() 함수에서 this.state에서 지정한 변수를 꺼내 사용할 수 있다.

728x90

'React' 카테고리의 다른 글

React 전개 연산자  (0) 2024.04.12
React 생명주기 함수 '변경'  (0) 2024.03.29
React Component 사용하기  (0) 2024.03.27
React 메인 바꿔보기  (0) 2024.03.27
React의 구조  (0) 2024.03.27