[react]
[react - 기초] class 방식의 컴포넌트 생명 주기
미나미나미
2020. 11. 9. 19:38
class 방식의 컴포넌트 생명 주기
# 맨 아래의 전체 소스 코드가 있습니다.
# 리액트 공식문서 : https://ko.reactjs.org/docs/react-component.html
React.Component – React
A JavaScript library for building user interfaces
ko.reactjs.org
# componentDidMount
- 컴포넌트 시작시 실행됨.
/*
* 마운트
- 컴포넌트의 인스턴스가 생성되어 DOM 상에 삽입될 때에 순서대로 호출
1. constructor()
2. static getDerivedStateFromProps()
3. render()
4. componentDidMount
*/
componentDidMount(){
console.log('componentDidMount');
console.log(arguments);
console.log('컴포넌트가 처음 실행시 동작함');
}
# componentDidUpdate
/*
https://ko.reactjs.org/docs/react-component.html
* 업데이트
- props 또는 state가 변경되면 갱신이 발생.
1. static getDerivedStateFromProps()
2. shouldComponentUpdata()
3. render()
4.
*/
componentDidUpdate(prevProps, prevState, snapshot){
console.log('componentDidUpdate=======================');
console.log(arguments);
console.log("prevProps" , prevProps);
console.log("prevState" , prevState);
console.log("snapshot" , snapshot);
console.log('=======================componentDidUpdate');
}
# componentWillUnmount
- 파일 갱신으로 인한 componetDidMound 확인하기(Hot-loader module로 업데이트됨.)
/*
- 컴포넌트가 DOM 상에서 제거될 때에 호출됩니다.
*/
componentWillUnmount(){
// 화면이 끝나기전에 실행이됨.
console.log('componentWillUnmount=======================');
console.log(arguments);
console.log('=======================componentWillUnmount');
}
# 전체소스코드
import React, { Component } from 'react';
class ComponentMountTest extends Component{
state = {
title : 'ComponentMountTest',
num : 0
};
/*
* 마운트
- 컴포넌트의 인스턴스가 생성되어 DOM 상에 삽입될 때에 순서대로 호출
1. constructor()
2. static getDerivedStateFromProps()
3. render()
4. componentDidMount
*/
componentDidMount(){
console.log('componentDidMount');
console.log(arguments);
console.log('컴포넌트가 처음 실행시 동작함');
console.log('aaa');
}
/*
https://ko.reactjs.org/docs/react-component.html
* 업데이트
- props 또는 state가 변경되면 갱신이 발생.
1. static getDerivedStateFromProps()
2. shouldComponentUpdata()
3. render()
4.
*/
componentDidUpdate(prevProps, prevState, snapshot){
console.log('componentDidUpdate=======================');
console.log(arguments);
console.log("prevProps" , prevProps);
console.log("prevState" , prevState);
console.log("snapshot" , snapshot);
console.log('=======================componentDidUpdate');
}
/*
- 컴포넌트가 DOM 상에서 제거될 때에 호출됩니다.
*/
componentWillUnmount(){
// 화면이 끝나기전에 실행이됨.
console.log('componentWillUnmount=======================');
console.log(arguments);
console.log('=======================componentWillUnmount');
}
onIncreseNum = () =>{
this.setState((prev)=>{
return {
num : prev.num + 1
}
})
}
onDecreseNum = () =>{
this.setState((prev)=>{
return {
num : prev.num - 1
}
})
}
render(){
const {title, num} = this.state;
return(
<>
<h1>{title}</h1>
<h1>{num}</h1>
<button onClick={this.onIncreseNum}>+</button>
<button onClick={this.onDecreseNum}>-</button>
</>
)
}
}
export default ComponentMountTest;