React_생명 주기 메소드

김귤·2023년 2월 8일
0

REACT

목록 보기
2/3
post-thumbnail

1. 생명주기 메소드(LifeCycle)이란?

: 모든 생명은 탄생하고, 성장하고, 소멸한다. 코드 역시 그러한 일련의 과정을 거치는데 그것이 바로 생명 주기 메소드, LifeCycle이다.
그 중에서도, 클래스형 컴포넌트는 생명 주기의 과정을 거친다. 생성과 업데이트, 제거의 3가지 단계를 각 코드의 위치에서 발생하기에 유지보수가 까다로운 편이다.

2. 생명주기 메소드의 단계

  • 생성 : construnctor / componentDidMount / render
  • 업데이트 : componentDidUpdate
  • 소멸 : componentDidWillUnmount

그 외, shouldComponentUpdate나 componentDidCatch() 등이 있으나 기존에도 잘 이용되지 않는 메소드이기 때문에 생략한다.

3. 생명주기의 '생성'

  • constructor
export default class CartList extends React.Component {
	constructor(props) {
    	super(props);
    	this.state = {
    		cartList: [],
      		allChecked: true,
      		shipCost: [],
    	}
 	}
}

클래스형 컴포넌트를 실행할 때, 가장 처음 보게 되는 생성자 메소드이다. 이것으로 state를 통해서 변수를 지정할 수 있게 되는 것이다.
뒤에 따르는 super(props)를 함께 실행해야 하며, 화면이 변경되고 다시 실행되지 않는다.

  • render
render(props) {
    if (props.value) {
      if (this.type === "number" || this.type === "float") {
        let val = props.value.toString().replace(",", "");
        if (isNaN(val) !== false) {
          alert("숫자만 입력 가능합니다");
          return false;
        }
      }
      let value = this.formatter(props);
      // 입력된 값으로 변경
      this.el.textContent = value;
    } else {
      this.el.textContent = "";
    }
    this.el.classList.add("ml-2");
    this.el.classList.add("mr-2");
  }요

(사실, render가 componentDidMount보다 뒤에 있지만, 이해를 휩게 하기 위해서 먼저 설명한다.) 클래스형 컴포넌트에서 반드시 있어야 하는 유일한 메소드이다. construnctor나 componentDidMount의 경우, 부재함에도 그 기능이 이루어지나 render의 경우 화면이 그려지지 않는 점이 특징이다. 이 메소드에서는 주로 this.props 혹은 this.state의 값이 활용된다. 주의할 점은 바로 이 메소드에서 setState를 실행하면 안 된다는 점이다.

  • componentDidMount
  async componentDidMount() {
    const userInfo = await decodeToken();
    if (
      Number(userInfo.payload.mb_grade) > 1 ||
      +userInfo.payload.discount > 0
    ) {
      await this.setState({ is_member: true });
    }

	this.setState({ mb_id: userInfo.payload.mb_id });

    
    this.setState({ biz_type: userInfo.payload.biz_type });
    
    this.setState({
      except_delivery_price: +userInfo.payload.except_delivery_price,
    });

    await this._getCartList();
    this.setState({
      checkedIdxList: this.state.allIdxList,
    });
    this._setCheckedData();
    const couponList = await getCouponList();
    this.setState({ couponList: couponList });
  }

컴포넌트가 생성된 후, 호출되는 메소드다. 특히 외부에서 데이터를 불러와야할 때 적절하게 사용되는 부분이다. 주로 비동기 처리나 자바스크립트 프레임워크의 연동인 이 메소드에서 이용된다. 또한 setState componentDidMount에서 즉시 호출되는 경우도 있는데, 이는 추가적인 렌더링이 발생할 수도 있다. 다시 말해, render의 과정이 두 번 발생하는 거지만 사용자는 이것을 볼 수 없다.

4. 생명주기의 '업데이트'

  • componentDidUpdate
 componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps != this.props) {
      this.setRequestParams();
    }
  }

업데이트 요소이기 때문에, 최초로 렌더링에서 호출되지 않고 갱신 직후에 호출된다. 컴포넌트의 갱신에서 DOM을 조작할 때 사용하기 좋은 메소드이다. 기존과 현재의 props를 비교하여 네트워크 요청을 할 때도 이 메소드가 활용된다.

또 하나의 특징은 바로 componetDidMount처럼 setState를 호출할 수 있다는 점이다. 그러나 해당하는 조건문이 제대로 설정되지 않는다면, 매번 갱신할 때마다 무한반복이 이루어지게 된다.

5. 생명주기의 '제거'

  • componentWillUnmount()
    이 역시 컴포넌트 마운트가 해제되어 제거되기 직전에 호출되는 함수이다. 주로 타이머 제거, 네트워크의 요청 취소 등을 사용한다. 다시 렌더링 되지 않는 것을 넣는 메소이다보니 setState가 필요한 경우, 추가하면 안 되는 곳이기도 하다.

계속.....

0개의 댓글