-
[ReactJS] Component Life Cycle methodIT Tech/찍어먹는 IT 2020. 9. 29. 14:22
ReactJS 는 컴포넌트 기반의 프레임워크이며 클래스들은 상속보단 합성이 되어 사용이 된다
컴포넌트엔 라이프 사이클 메소드들이 존재하며 React에서 기본적으로 제공되는 함수들이 존재한다
컴포넌트가 DOM 상에 들어갈 때 Mounting 이라고 하는데
순서대로 사용되는 함수들이 있다. 대표적으로
Mounting
- contruntor() : 자바스크립트에 해당되는 부분이라 봐도 되며, 생성자라 가장 먼저 초기화된다
- static getDrivedStateFromProps() : 자주 사용하지 않다고 하나, 컴포넌트가 업데이트 될 때 사용이 되는 함수
- render() : 실질적으로 뷰에 해당되는 부분이며, html 코드 삽입을 해주는 부분이다
- componentDidMonut() : 렌더링된 직후에 호출되는 부분이며, 최초 마운트에서 최종단 함수
마운트가 끝나고 이제 사용자가 버튼을 누른다거나 해서 상태에 변화가 생긴다면
Updating (업데이트) 이 발생이 되는데 다음과 같은 순서대로 함수가 실행이 된다.
Updating
- static getDerivedStateFromProps() : Mounting에서도 사용되었던 함수이며 State나 Props의 변경을 받아들이는 함수로 봐도 될까 싶다
- shouldComponentUpdate() : 컴포넌트의 변화를 React가 감지 여부
- render() : 마운트와 동일하게 html 코드를 이용해서 렌더링이 되는 부분
- getSnapshotBeforeUpdate() : 마지막으로 렌더링된 결과가 DOM에 반영이 되었을 때 호출되는 함수. 이 함수의 반환된 인자가 componentDidUpdate로 전달이 된다고도 하고 채팅 스크롤 위치 탐지에 적용할 수 있다고도 한다
- componentDidUpdate() : 마운트와 달리 update가 실행 되고 있다. 최초 렌더링에는 나타나지 않는 부분이다.
마지막으로 컴포넌트가 DOM 상에서 제거될 때, 사용되는 Unmount가 있다.
Unmount
- componentWillUnmount() : 컴포넌트가 제거되기 직전에 호출되는 함수이며, ComponentDidMount()의 정보들을 제거할 때 사용된다
import React from 'react'; // import PropTypes from 'prop-types'; class App extends React.Component { state = { count: 0 }; add = () => { console.log("add"); this.setState(current => ({count: current.count + 1})); }; minus = () => { console.log("minus"); this.setState(current => ({count: current.count - 1})); }; componentDidMount() { console.log("Component did Mount"); }; componentDidUpdate() { console.log("Component did Update"); } render() { console.log("rendering!"); return ( <div> <h1>The number is : {this.state.count}</h1> <button onClick={this.add}> Click</button> <button onClick={this.minus}> Click</button> </div> ) } } export default App;
반응형'IT Tech > 찍어먹는 IT' 카테고리의 다른 글
[Docker] 도커(Docker) 란? (0) 2020.10.31 [OpenCV] OpenCV 윈도우 개발 환경 및 예제 (0) 2020.10.02 [ReactJS] ReactJS App 만드는 방법 (0) 2020.09.27 시큐어 코딩 가이드 (0) 2020.09.27 TCP : 3, 4 Way Handshake 연결, 전송, 종료 과정 (0) 2020.09.20