Component Life Cycle

이재진·2021년 4월 28일
0
post-thumbnail

Component Life Cycle

라이프 사이클 메쏘드는 기본적으로 리액트가 컴포넌트를 생성하는 그리고 없애는 방법이다.

마운팅(mounting)은 태어나는 것과 같다
업데이팅은 일반적인 업데이트
언마운팅은 컴포넌트가 죽는 걸 의미 (페이지가 바뀔 때)

마운팅(mounting)
constructor() ->
컴포넌트가 마운트 될 때, 컴포넌트가 스크린에 표시 될 때, 컨스트럭터가 호출 된다.
render() -> 렌더 후
componentDidMount()
이렇게 되면 기본적으로 처음 render 되었다는 걸 알 수 있다.

class App extends React.Component {
  state = {
    count: 0, //내가 바꿀 데이터를 state에 넣는다
  };

  add = () => {
    this.setState((current) => ({ count: current.count + 1 }));
  };
  minus = () => {
    this.setState((current) => ({ count: current.count - 1 }));
  };
  componentDidMount() {
    console.log("Component rendered"); //2
  }

  render() {
    console.log("I'm rendering");  //1
    return (
      <div>
        <h1>The number is {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

class App extends React.Component {
  state = {
    count: 0, //내가 바꿀 데이터를 state에 넣는다
  };

  add = () => {
    this.setState((current) => ({ count: current.count + 1 }));
  };
  minus = () => {
    this.setState((current) => ({ count: current.count - 1 }));
  };
  componentDidMount() {
    console.log("Component rendered");
  }
  componentDidUpdate() {
    console.log("I just updated");
  }

  render() {
    console.log("I'm rendering");
    return (
      <div>
        <h1>The number is {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

add 또는 minus를 클릭해서 state를 변경 할 때가 업데이트다.
add를 클릭해서 "I'm rendering" 나오고 그 후 "I just updated" 가 나온다.

setstate를 호출하면 컴포넌트를 호출하고, 먼저 render를 호출한 다음 업데이트가 완료되었다고 말하면 componentDidUpdate가 실행된다.

profile
개발블로그

0개의 댓글