본문 바로가기

react , js 공부

[react] Lifecycle이란 (Mount,PropsUpdate,StateUpdate..)

반응형

생명주기 이다.

 

컴포넌트가 실행되거나 업데이트되거나 제거될 때, 특정한 이벤트들이 발생한다

 

 

 

한 번에 이해 할 수있는 그림이다 

 


Mount

 

컴포넌트가 처음 실행될 때 그것을 Mount라고 한다

 

① 컴포넌트가 시작되면 context,  defaultProps, state를 저장한다

 

② componentWillMount 메소드를 호출한다

 

③ render로 컴포넌트를 DOM에 부착한다

 

④ Mount가 완료된 후 componentDidMount가 호출된다 

 

 

 

주의:

componentWillMount 에서는 Mount중 이기 때문에 pops나 state를 바꾸면 안된다 

그리고 아직 render하지 않았기 때문에 DOM에도 접근 할 수 없다

 

componentDidMount 에서는 DOM에 접근할 수 있다 때문에 주로 AJAX 요청하거나

setTimeout, setInterval 같은 행동을 한다

 

요약하자면

 

state, context, defaultProps 저장 -> componentWillMount  -> render -> componentDidMount

 

 


Props Update

 

 

props가 없데이트 될 때의 과정이다

 

업데이트되기 전에 업데이트가 발생하였음을 감지하고, componentWillReceiveProps 메소드가 호출된다

 

그 후 shouldComponentUpdate 호출 -> componentWillUpdate 호출 -> render -> componentDidUpdate 가 된다

 

이 메소드들은 첫 번째 인자로 바뀔 props에 대한 정보를 가지고 있다

 

componentDidUpdate만 이미 업데이트되었기 때문에 이전의 props 정보를 가지고 있다

 

 

shouldcomponentUpdate에서는 아직 render하기 전이기 때문에 return false를 하면 render을 취소할 수있다

 

주로 여기서 성능 최적화를 하는데 쓸데없는 update가 일어나면 걸러낸다

 

 

 


State Update

 

setState 호출을 통해 state가 업데이트될 때의 과정이다 props update와 과정이같지만

 

componentWillReceiveProps는 호출되지 는다

 

마찬가지로

 

shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate

 

 

 


Unmount

 

컴포넌트가 제거되는 것을 Unmount라고 한다 

 

componentWillUnmount는 컴포넌트를 사용하지 않을때 발생하는 이벤트다

 

(이미 제거된 컴포넌트에서 이벤트발생 할 수는 없기에 componentDidUnmount같은건 없다)

 

 

용도에 맞지않는 메소드를 사용하면 React에서 자체적으로 에러 메시지를 띄워준다

 

예를들어 componentDidMount나 render에 setState를 사용한경우

 

 

 


Error

 

에러 발생 시를 위한 componentDidCatch가 있다

 

componentDidCatch(error, info){
  console.error(error, info);
}

최상위 컴포넌트에 한 번만 넣어주면 된다 에러 발생시 어떻게 대처할 것인가 정의할 수 있다

 

 

 


 

 

 

참조: www.zerocho.com/category/React/post/579b5ec26958781500ed9955

반응형