FrontEnd/React.js

React의 생명주기-생성

J._.cobb 2022. 6. 23. 20:55

React에서 생명주기란

comopnent의 생성, 변경, 소멸 과정을 뜻한다.

 

생성

  • render()
  • constructor()
  • getDerivedStateFromProps()
  • componentDidMount()

render()

return되는 html 형식의 코드를 화면에 그려주는 함수이다.

화면 내용이 변경돼야 할 시점에 자동으로 호출된다.

Constructor()

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

component 내부에서 사용되는 변수(state)를 선언하고 부모 객체에서 전달받은 변수(props)를 초기화할 때 사용한다.

super() 함수는 가장 위에 호출해야 한다.

getDerivedStateFromProps()

getDerivedStateFromProps(props, state) 함수는 constructor() 함수 다음으로 실행된다.

컴포넌트가 새로운 props를 받게 됐을 때 state를 변경해준다.

App.js에서 전달한 prop_value라는 변수를 props.prop_value로 접근해 값을 가져올 수 있다.

componentDidMount()

componentDidMount() 함수는 작성한 함수들 중 가장 마지막으로 실행된다.

render()함수가 return되는 html 형식의 코드를 화면에 그려준 후 실행된다.

화면이 모두 그려진 후에 실행돼야하는 이벤트 처리, 초기화 등 가장 많이 활용되는 함수이다.

 

 

예제코드

 

R007_LifecycleEx.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 FUNCTION] </h2>
    )
  }
}

export default R007_LifecycleEx;

 

App.js

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

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

export default App;

 

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: <https://bit.ly/CRA-vitals>
reportWebVitals();

 

App.css

div{
  background-color: rgb(162, 127, 243);
  color: rgb(255, 255, 255);
  padding: 40px;
  font-family: 고딕;
  text-align: center;
}

h1{
  color: white;
  background-color: #2EFE2E;
  padding: 10px;
  font-family: 궁서;
}