갬발자의 프로그래밍/React

리액트 뽀개기 (4)

코라제이 2020. 1. 2. 12:02

라이프 사이클을 알아보자. 

 

 

React Lifecycle Methods diagram

Fully interactive and accessible React Lifecycle Methods diagram.

projects.wojtekmaj.pl

리액트에서 제공하는 라이프 사이클인데 한글로 되어있으니 어렵지 않게 알아볼 수 있다.

찾아보면 render와 getDerivedStateFromProps는 마운트와 업데이트 모두에 속한다.

라이프 사이클의 함수들은 아래와 같다. (16.3 이상의 버전)

//Life.js

//마운트
constructor(props) {}
static getDerivedStateFromProps(props, state){}
componentDidMount(){}
UNSAFE_componentWillMount(){}
render(){}
// 업데이트
    
shouldComponentUpdate(nextProps, nextState){}
getSnapshotBeforeUpdate(){}
componentDidUpdate(){}
UNSAFE_componentWillUpdate(){}
UNSAFE_componentWillReceiveProps(props){}
    
// 마운트 해제
componentWillUnmount(){}
    
render(){}

우선constructor() 와 render()는 많이 봤다 

리액트 뽀개기 (3)에서 componentDidMount(){} ,componentWillUnmount(){} 사용해봤다.

 

리액트 뽀개기 (3)

state를 알아보자. state는 클래스에서만 사용이 가능하다 props와 비슷하지만 컴포넌트에 의해 완전히 제어되며 private속성이다. 일단 함수 컴포넌트에서 클래스 컴포넌트로 조금 수정을 했다. import React fro..

191125.tistory.com

 

UNSAFE_componentWillMount()이함수는 componentWillMount()의 대한 새로운 표기 함수다 UNSAFE_ 를 붙이는 이유는 '"안전하지 않은"은 보안을 의미하는 것이 아니라, 이러한 수명주기를 사용하는 코드가 향후 비동기 렌더링이 활성화된 경우 이후 버전의 React에서 버그가 있을 가능성이 높다는 것을 나타냅니다'라고 리액트에서 말한다  

따라서 UNSAFE_는 별개로 진행하지 않을 것이다. 자세히 알아보고 싶을 경우

 

Update on Async Rendering – React Blog

For over a year, the React team has been working to implement asynchronous rendering. Last month during his talk at JSConf Iceland, Dan unveiled some of the exciting new possibilities async rendering unlocks . Now we’d like to share with you some of the le

reactjs.org

 

다음은 아래의 함수를 알아보자.

 static getDerivedStateFromProps(props, state){
        if(state.a !== props.a){
            return {
               a : 100
            }
        }
        return null;
    }

이것은 상태 값으로 객체를 넘겨주면 되는 함수이다. props의 값이 변할 때 state를 설정해주는 함수이다. 

결과

업데이트 함수를 알아보자.

    shouldComponentUpdate(nextProps, nextState){
        if(){...}
        return true;
        
    }

위 함수는 오직 성능 최적화만을 위한 함수이다. 잘 사용되지 않으며, 기본적으로 true를 반환 해부면 false일 경우 render()와 componentDidUpdate()와 UNSAFE_componentWillUpdate()는 호출되지 않는다.

 

다음은 아래 함수를 알아보자.

   componentDidUpdate(nextProps,nextState){
        if(this.props.a !== nextProps.a)
            console.log("componentDidUpdate");
    }

최초 렌더링에서는 호출되지 않으며 갱신된 직후 호출된다.  DOM을 조작하기 위하여 사용하면 좋다.

 

결과

마지막으로 마운트 해제 함수에 대해서 알아보자.

componentWillUnmount(){console.log('unmount')}

컴포넌트가 마운트 해제되어 제거되기 직전에 호출된다. setState()를 호출하면 안 되고 해체되면 다시 마운트 되지 않는다.

결과

소스는  깃허브에서 찾아볼 수 있다.

https://github.com/justdotiung/studyreact