React
[React] 클래스형 컴포넌트 생명주기
로니콜먼
2020. 8. 16. 21:19
생명주기 함수
- componentDidMount : 컴포넌트가 처음 화면에 그려지면 실행
- componentDidUpdate : 화면이 업데이트 됐을 때 실행
- componentWillUnmount : 컴포넌트가 화면에서 떠날 때 실행
실행 순서
constructor() -> render() -> componentDidMount()
-> (이벤트 발생 시) componentDidUpdate() -> render()
-> componentWillUnmount()
import React from 'react';
//App클래스가 React.Component를 상속받았으므르
//App클래스에 React.Component의 기능이 추가된다
//클래스형 컴포넌트를 사용하는 이유 : state를 사용하기 위함
class App extends React.Component{
//생명주기 함수는 아니지만 클래스형 컴포넌트가 생성될 때 실행
constructor(props){
super(props);
console.log('hello');
}
//컴포넌트가 처음 화면에 그려지면 실행
componentDidMount(){
console.log('component rendered');
}
//화면이 업데이트 됐을 떄
componentDidUpdate(){
console.log('I just updated');
}
//컴포넌트가 화면에서 떠날때 실행
componentWillUnmount(){
console.log('Goodbye, cruel world');
}
state = {
count: 0,
};
add = ()=> {
this.setState(current =>({
count : current.count +1
}));
};
minus = ()=> {
this.setState(current =>({
count : current.count -1
}));
};
render(){
console.log("I'm rendering");
return (
<div>
<h1>The number is : {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
export default App;