[React] 5 - Component > 컴포넌트의 생명주기

jungeundelilahLEE·2021년 2월 14일
1

React

목록 보기
10/24

goal

  • component 생명주기의 모든 것

컴포넌트의 생명주기

  • 모든 컴포넌트는 여러 종류의 “lifecycle methods”를 가지며, 이 메서드를 오버라이딩하여 특정 시점에 코드가 실행되도록 설정할 수 있다.

  • 클래스 컴포넌트는 항상 props로 기본 constructor를 호출해야 한다
    • 마운트 : DOM 에 렌더링 될 때마다
    • 삭제 : DOM 이 삭제될 때마다
  • 클래스 컴포넌트에서 "특정 메서드"를 사용해서 컴포넌트가 (un)마운트 될 때, 일부 코드를 작동시킬 수 있다.
  • 이때 사용되는 "특정 메서드" 를 생명주기 메서드라고 부른다.

constructor
해당 컴포넌트가 " 마운트되기 전"에 호출된다.

render
"데이터가 변경되어 새 화면을 그려야 할 때 자동으로 호출"된다.
render() 함수가 반환하는 JSX를 화면에 그린다.

componentDidMount()
"render() 함수가 JSX를 화면에 그린 이후"에 호출되는 함수이다. (= 컴포넌트 출력물이 DOM에 렌더링 된 이후)
컴포넌트가 화면에 모두 표현된 이후 해야 하는 작업들을 여기서 진행하게 된다.

componentDidUpdate()
"컴포넌트가 실제 화면에 출력된 이후" 호출되는 함수이다.
이 함수는 부모 컴포넌트로부터 전달된 이전 props 와, 이전 state을 인자로 전달받는다.
DOM의 정보를 변경할 때 사용한다.

componentWillUnmount()
"컴포넌트가 소멸되기 직전"에 호출되는 함수이다.


마운트 (Mounting)

=> when an instance of a component is being created and inserted
: 컴포넌트의 인스턴스가 생성되고 DOM에 삽입 될 때, 순차적으로 호출된다.

  • constructor()
  • render()
  • componentDidMount()
  • static getDerivedStateFromProps()

업데이트 (Updating)

=> when a component is being re-rendered
: (props or state가 변경되면 갱신이 발생한다.) 컴포넌트가 다시 렌더링 될 때 순차적으로 호출된다.

  • render()
  • componentDidUpdate()
  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • getSnapshotBeforeUpdate()

마운트 해제 (Unmounting)

=> when a component is being removed
: 컴포넌트가 DOM에서 제거될 때 호출된다.

  • componentWillUnmount()

오류 해제 (Error Handling)

=> when there is an error during rendering
: 자식 컴포넌트를 렌더링하거나, 자식 컴포넌트가 생명주기 메서드를 호출하거나, 또는 자식 컴포넌트가 생성자 메서드를 호출하는 과정에서 오류가 발생했을 때에 호출된다.

  • static getDerivedStateFromError()
  • componentDidCatch()

render()

  • render() 메서드는 class component에서 반드시 구현되어야 한다.
  • render() 메서드가 호출되면, this.props or this.state의 값을 활용해서 아래 중 하나를 반환해야 한다.
    • React elements
    • Arrays and Fragments
    • Portals
    • String and Numbers
    • Boolean 또는 null
  • render() 는 component의 state를 변경하지 않는다.
  • render() 는 호출될 때마다 동일한 결과를 반환해야 한다.
  • render() 는 브라우저와 직접적으로 상호작용하지 않는다.

constructor(props)

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}
  • 인스턴스에 이벤트 처리 메서드를 bind 하거나 (this.state에 객체를 할당해서) local state를 초기화하기 위해 사용한다. if 앞의 작업이 필요없다면, 해당 react component에는 constructor를 구현하지 않아도 무방하다.
  • constructor는 해당 component가 "마운트되기 전"에 호출된다.
  • React.Component를 상속한 component의 constructor를 구현할 때에는, super(props)를 가장 먼저 호출해야 한다. (안하면, this.props가 constructor내에서 정의되지 않아 버그 발생 가능)
  • constructor() 내부에서 setState()를 호출하면 안된다.
  • local state가 필요할 경우, constructor 내에서 this.state에 초기 state값을 할당한다.
    (constructor는 this.state를 "직접" 할당할 수 있는 유일한 곳이다. /
    그 외의 메서드에서는 this.setState()를 사용해야 한다.)
  • constructor() 내부에서는 side-effects or subscriptions 을 발생시키면 안되며, 필요할 경우 componentDidMount()를 사용한다.
  • 주의! state에 props를 복사하는 것은 되도록 피한다.
constructor(props) {
 super(props);
 // Don't do this!
 this.state = { color: props.color };
}

ex

class Clock extends React.Component {
  constructor(props) {
    super(props);
    //! this.state = {}
    // 현재 시간을 표시해야 하기 때문에 현재 시간이 포함된 객체로 this.state를 초기화하는 작업을 여기서 한다.
    // 아래에서 이 state를 업데이트 하게 된다.
    this.state = {date: new Date()};
  }
  
 
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
    // # 여기에서의 코드로
  }
  
  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  // # 여기서
  // 해당 컴포넌트는 setState()에 현재 시각을 포함하는 객체를 호출하면서 UI 업데이트를 진행한다.
  // setState()를 호출하며, 리액트는 state가 변경된 것을 인지한다. 
  // 그리고 화면에 표시될 내용을 알아내기 위해 다시 render() 메서드를 호출한다. 
  // ## 다시 render() 로 가면 
  tick() {
    this.setState({
      date: new Date()
    });
  }

  //! render()
  // 리액트는 해당 컴포넌트의 render() 메소드를 호출한다.
  // 이를 통해서 리액트는 화면에 표시되어야 할 내용을 알게 된다.
  // 이후 리액트는 해당 컴포넌트의 렌더링 출력값을 일치시키기 위해 DOM을 업데이트 한다.
  // 해당 컴포넌트의 출력값이 DOM에 삽입되면, 리액트는 componentDidMount() 메서드를 호출한다. 
  
  // ## 다시 여기서
  // 이 과정에서 render() 메서드 안의 this.state.date가 변경되면서, 렌더링되는 값은 업데이트된 시각을 포함하게 된다.
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

profile
delilah's journey

0개의 댓글