생명주기
컴포넌트가 DOM트리에 렌더링되기까지의 과정을 마운트라고 한다
생명주기 함수들 중에 지금 알아볼 함수는 componentDidMount, componentWillUnmount이다
componentDidMount
class Count extends React.Component{
constructor(props) {
super(props);
this.state = {
cnt : 0
}
}
counting(number){
return number +=1;
}
render() {
this.state.cnt = this.counting(this.state.cnt);
return (
<div>
<h2>{this.state.cnt}</h2>
</div>
)
}
}
function Start(){
ReactDOM.render(
<Count />,
document.getElementById('root'),
);
}
setInterval(Start, 1000);
이전 포스팅에서 본 코드로 확인해 보면
this.statte.cnt가 화면에 렌더되고 마운트가 끝나고 나면
componentDidMount함수가 호출된다
위 코드에선 명시해주지 않았기 때문에 아무런 일을 하지 않지만
class Count extends React.Component{
constructor(props) {
super(props);
this.state = {
cnt : 0
}
}
componentDidMount() {
this.timerID = setInterval(
() => this.counting(), 1000
)
}
counting() {
this.setState({
cnt: this.state.cnt + 1
});
}
render() {
return (
<div>
<h2>{this.state.cnt}</h2>
</div>
)
}
}
function Start(){
ReactDOM.render(
<Count />,
document.getElementById('root'),
);
}
Start();
위와 같이 설정해주게 되면 제일 처음 0이 렌더된 이후에 setInterval로 1초마다 counting함수를 불러와 state값을 수정,
그것을 인지하고 다시 렌더, 다시 수정...
반복해서 숫자가 올라가게된다
componentWillUnmount
DOM에서 클래스 컴포넌트가 한번이라도 언마운트, 즉 없어진 적이 있다면 이 함수가 호출된다
...
componentDidMount() {
this.timerID = setInterval(
() => this.counting(), 1000
)
}
componentWillUnmount() {
clearInterval(this.timerID);
}
...
보통 이런식으로 이전에 주었던 이벤트들을 회수하기 위해 사용된다