코딩하는 문과생

[React.js] Life Cycle API 본문

웹 프로그래밍/React.js

[React.js] Life Cycle API

코딩하는 문과생 2020. 6. 21. 12:54

[Life Cycle API]

컴포넌트가 브라우저 내 나타나고, 사라지고, 업데이트 될 때 호출되는 API

 

[컴포넌트 초기 생성]

Constructor
constructor(props) {
  super(props);
}

 

ComponentDidMount

컴포넌트가 화면에 나타날 때 호출

1. 외부라이브러리 연동

2. 필요한 데이터를 요청하기 위해 axios, fetch 등을 통한 ajax요청

3. DOM의 속성을 읽거나 직접 변경하는 작업

componentDidMount() {

}

 

[컴포넌트 업데이트]

shouldComponentUpdate

컴포넌트 최적화 작업에 사용

1. React는 DOM과 Virtual DOM간 비교를 통해 변화된 부분만 비동기적으로 리렌더링시킨다.

2. 변화가 없다는 것은 리렌더링된 Virtual DOM을 DOM과 비교해 변화된 부분이 없다는 것을 뜻한다.

3. 즉, Virtual DOM은 이벤트가 발생할 때마다 리렌더링이 된다는 의미이다.

4. 부모가 리렌더링되면, 자식들도 모두 렌더링 되기 때문에(render함수의 호출) 컴포넌트 수가 많아지면 CPU에 과부하를 줄 수 있다.

5. 불필요한 Virtual DOM 리렌더링을 위해 shouldComponentUpdate가 필요하다.

6. default는 true를 반환하지만, false를 반환시킬경우 render 함수를 호출하지 않는다.

shouldComponentUpdate(nextProps, nextState) {

  return true;
}

 

ComponentDidUpdate

render() 호출이후 발생

1. this.props와 this.state가 변경되어 있다.

2. 파라미터를 통해 이전 props와 state조회 가능

componentDidUpdate(prevProps, prevState, snapshot) {

}

[컴포넌트 제거]

componentWillUnmount

이벤트, setTimeout 등 제거

import React, {Component} from 'react';

class Counter extends Component {

    state = {
        number: 0
    }

    constructor(props) {
        super(props);
        console.log('constructor');
      }

      componentDidMount() {
        console.log('componentDidMount');
      }
    
      shouldComponentUpdate(nextProps, nextState) {
        // 3 의 배수라면 render함수를 호출하지 않는다.
        console.log('shouldComponentUpdate');
        if (nextState.number % 3 === 0) return false;
        return true;
      }

      componentDidUpdate(prevProps, prevState) {
        console.log('componentDidUpdate');
      }
      
    
      handleIncrease = () => {
        const { number } = this.state;
        this.setState({
          number: number + 1
        });
      }
    
      handleDecrease = () => {
        this.setState(
          ({ number }) => ({
            number: number - 1
          })
        );
      }
      
      render() {
        console.log('render');
        return (
          <div>
            <h1>카운터</h1>
            <div>값: {this.state.number}</div>
            <button onClick={this.handleIncrease}>+</button>
            <button onClick={this.handleDecrease}>-</button>
          </div>
        );
      }
    }

export default Counter

 

개발자도구로 확인가능

[컴포넌트 에러발생]

componentDidCatch

1. 존재하지 않는 함수 호출시

2. 호출한 배열이나 객체가 존재하지 않을 때

이와 같은 방법으로 처리 가능

import React, {Component} from 'react';

const Problematic = () => {
    throw(new Error('버그발생!')); //2. 에러를 발생시킨다.
    return (
        <div>

       </div>
    );
};

class Counter extends Component {

    state = {
        number: 0,
        error: false
    }

    constructor(props) {
        ...
      }

      componentDidMount() {
        ...
      }
    
      shouldComponentUpdate(nextProps, nextState) {
       ...
      }

      componentDidUpdate(prevProps, prevState) {
        ...
      }
      
    
      handleIncrease = () => {
        ...
      }
    
      handleDecrease = () => {
        ...
      }
      
    componentDidCatch(error, info){ //3. 해당 라이프 사이클 함수가 error state를 true로 변경
        this.setState({
            error: true
        });
    }

      render() {
        if(this.state.error) return (<h1>에러발생!</h1>); 
        // 4. if문 내 true가 되어 "에러발생" 화면에 노출 
        return (
          <div>
            <h1>카운터</h1>
            <div>값: {this.state.number}</div>
            {this.state.number === 4 && <Problematic />} 
            {/* 1. 에러 발생하는 컴포넌트 호출 */}
            <button onClick={this.handleIncrease}>+</button>
            <button onClick={this.handleDecrease}>-</button>
          </div>
        );
      }
    }

export default Counter

 

'웹 프로그래밍 > React.js' 카테고리의 다른 글

[React.js] React Hook  (0) 2021.09.05
[React.js] Props & State  (0) 2020.06.21
[React.js] 프로젝트 구성, JSX  (0) 2020.06.21
[React.js] React 개발환경설정  (2) 2020.06.21