본문 바로가기
React를 같이 배워보자

React 4일차-16.3v 이전 라이프사이클

by 멈추지않아 2022. 1. 23.

오늘은 라이프 사이클에대해서 알아보겠다.

우선 라이프 사이클이 무엇인지 알아보자.

한국어로 번역하면 삶의 순환 이다 즉 자연계순환처럼 생겨나고 죽기까지 과정의 과정을 알아보는것이다. 컴포넌트의 라이프 사이클은 컴포넌트의 순환체계이다 이게 언제 만들어지고 언제 우리눈에 보여지고 언제 데이터가 옮겨지고 등등 의 순서를 알아보는것이다. 즉 라이프 사이클은 순서를 알기위한 개념이다.

 

 

우선 평소처럼 스크립트에 내용 지우고 복사 붙여 넣기하자

class Com extends React.Component{

        state={
            age:39,
        };
        interval=null;
        constructor(props){
            super(props);
            console.log('constructor',props)
        };
        render(){
            console.log('render')
            return (
            <div>
                <h2>
                    Hello {this.props.name}-{this.state.age}
                </h2>
            </div>);
        };
        componentWillMount(){
            console.log('componentWillMount');
            this.interval=setInterval(() => {
                console.log('setinetrval');
                this.setState(state=>{
                    const newst={...state,age:state.age-1}
                    return newst;
                });
               
            }, 1000);
        };
        componentDidMount(){
            console.log('componentDidMount');
        };
        componentWillReceiveProps(nextprops){
            console.log("componentWillReceiveProps",nextprops)
        };
        shouldComponenetUpdate(nextprops,nextstate){
            console.log("shouldComponenetUpdate",nextprops,nextstate)
            return true;
        };
        componentWillUpdate(nextprops,nextstate){
            console.log("componentWillUpdate",nextprops,nextstate)
        };
        componentDidUpdate(preprops,prestate){
            console.log("componentDidUpdate",preprops,prestate);
           
        };
        componentWillUnmount(){
            clearInterval(this.interval);
            console.log("componentWillUnmount")
        }
       
    }
ReactDOM.render(<Com name="Boem" />,document.querySelector("#root"))

 

그리고 npx serve로 localhost열어버리자

 

이렇게 나올것이고 숫자가 한개씩 줄어들것이다.

 

우선 이론부터 설명하겠다.

크게 4개로 나뉜다 Mounting,Props Change,State Change,Unmounting

Mounting

initialization(state,props기본 설정 constructor 이 여기 포함)->componentWillMount(실행되기 전)
->render(실행)->componenetDidmount(실행되고 나서)

이런 순서로 진행 된다. 기본설정하고 적용되기전에 할거 미리하고 적용하고 적용하자마자 할거 하기 4단계로 구별된다.

propsChange(클래스외부로부터 받은 데이터 변경)

componentWillReceiveProps(props전달받고)-> shouldComponentUpdate(컴포넌트를 업데이트 시키고)->render(업데이트된상태로 실행)->componentDidUpdate(실행 하고 나서)

이거는 우선  데이터를 전달받고 그다음 컴포넌트를 그데이터로 변경하고 그걸 바탕으로 실행시키고 그다음 실행하고나서 적용할걸 적용한다.

State Change(클래스내부에서 만든 데이터 변경)

shouldComponentUpdate(컴포넌트를 업데이트 시키고)->componentWillUpdate(업데이트되기전)
->render(실행)->componentDidUpdate(실행 하고 나서)

Unmounting

componentWillUnmount(실행끝나고 삭제될때)

이제 켜놓은 localhost로 가서 ctrl+shift+i를 눌러보자

콘솔창

이런창이 뜰꺼다 그럼 여기 콘솔이찍히는데 한번 알아 보자

(실행되면 함수이름이 찍히도록 설정을 해놨다. props변경은 없어서 뜨지 않을것이도 unmount도 없을것이다.)

constructor->componentWillMount->render->componentDidMount->(setinetrval->componentWillUpdate ->render->componentDidUpdate)반복이다

우선 생성자로 기본 initialization이 실행 되고 그다음 componentWillMount실행되기전에  할것이 실행된다.

그다음 render로 실행이 되고 componentDidMount로 실행되고 할것이 실행되고 이제 1초마다 state값을 1씩 올라가게 해놨다. 그래서 (setinetrval->componentWillUpdate ->render->componentDidUpdate)이게 반복된다.

(setinetrval->componentWillUpdate ->render->componentDidUpdate) 이거는 우선 setinetrval시간이 1초 지나고

componentWillUpdate업데이트되기전 render실행 componentDidUpdate업데이트되고 나서 이런식으로 구성된다.

 

이제 위에 코드중에 모르는 부분에 대해서 설명하겠다.

 clearInterval(this.interval);

 

this.interval=setInterval(() => {
                console.log('setinetrval');
                this.setState(state=>{
                    const newst={...state,age:state.age-1}
                    return newst;
                });
               
            }, 1000);

이거 두개가 이해가 힘들것이다. 우선 밑에 꺼부터 설명 하겠다. 

setInterval이건 저번에 설명했지만 간단하게 설명하겠다. 두가지 요소를 전달하는데 함수 ,숫자 이두개가 전달되면 숫자 만큼 시간이 지날때마다 함수가 실행 되는것이다. 

{...state,age:state.age-1}이거는 전달받은것을 객체에넣고 거기 추가로 age에 전달받은값 안에 있는 age에서 1을뺀값을 저장하는 것이다.  만약 새로운것이면 추가 하고 기존에 있던것이면 덮어쓰게 된다.

현재 state에 age가 있으므로 덮어쓰게 된다.

clearInterval(this.interval);이건 바로 setinterval이걸 멈추는것이다. 괄호안에 있는 setinterval을 멈춰주는것인데 밑에있는 함수를 클래스내부에있는 interval이라는 변수에 저장해주었기때무에 this.interval은 밑에있는 함수를 가르키게 된다.

shouldComponenetUpdate(nextprops,nextstate){
            console.log("shouldComponenetUpdate",nextprops,nextstate)
            return true;
        };
여기서는 return값이 boolean타입 이어야한다 즉 true이거나 false둘중하나이어야한다.

16.3이전의 라이프 사이클에대해 알아봤다. 다음에는 16.3이후의 라이프 사이클을 알아보겠다.