본문 바로가기

basic/React.js

[React.js] Life Cycle 생명주기 함수 ①

리액트의 생명주기 = 컴포넌트의 생성, 변경 소멸의 과정을 뜻함

출처:  https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/  를 수정함

render(). constructor(), getDerivedStateFromProps(), componentDidMount() 함수는

componenet의 생성 과정에 속한다.

getDefaultProp(), getInitialState() 는 constructor로 대체 되었다.
constructor는 생명주기 함수중 가장 먼저 실행되며, 처음 한 번만 실행된다.

constructor에서 component 내부에서 사용되는 변수(state)의 선언과 초기화를 하고, 부모 객체에서 전달받은 변수(props)는 super에 던지면 된다. (super는 부모 클래스를 가리키는데 리액트에서는 React.Component를 가리킨다. 또한 super는 부모클래스 생성자이므로 첫줄에 위치해야 this를 사용할 수가 있다.

constructor(props) {
    super(props);
    this.state = {};
  }

render()는 html 코드를 화면에 그려주는 함수이다.

compoenentWill~~함수들 getDerivedStateFromProps(nextProps, prevState)로 대체가능하다.
다만 will함수들과 혼용해서 같이 사용하면 오류가 걸리는것 같다.
getDerivedStateFromProps함수는 최초 마운트 시와 갱신 시 모두에서 render 메서드를 호출하기 직전에 호출된다.=> constructor() 함수 다음에 바로 실행된다.

static getDerivedStateFromProps(nextProps, prevState){
    return {};
}

새로운props를 인자로 받아 기존의 state를 변경해준다.
객체를 return하지 않으면 오류가 난다.
만약 null을 반환한다면 state를 갱신하지 않는다.

componentDidMount는 컴포넌트가 마운트된 직후, 즉 트리에 삽입된 직후에 호출됩니다. DOM 노드가 있어야 하는 초기화 작업은 이 메서드에서 이루어지면 됩니다. 외부에서 데이터를 불러와야 한다면, 네트워크 요청을 보내기 적절한 위치입니다. => 이벤트 처리, 초기화 작업, 생성단계에서 가장 마지막에 실행된다.

 

  결론 : constructor() => getDerivedStateFromProps() => render() => componentDidMount() 의 순서로 호출된다.  

 

 

 

자세한 내용은 공식문서에서 확인할것!

https://ko.reactjs.org/docs/react-component.html#static-getderivedstatefromprops