리액트의 생명주기는 컴포넌트가 브라우저에 나타나고 업데이트 되거나 사라질 때 호출 되는 메서드이다!
즉 특정 시점에서 코드가 실행되도록 설정이 가능하다는 뜻이다!
import { Component } from "react";
import Router from "next/router";
export default class ClassCounterPage extends Component {
// 클래스형은 랜더 함수를 적어야 함
state = {
count: 0,
};
componentDidMount(): void {
console.log("그려지고 나서 실행!!");
}
componentDidUpdate(): void {
console.log("변경되고 나서 실행!!");
}
componentWillUnmount(): void {
console.log("사라지기 전에 실행");
// 예) 채팅방 나가기 API
}
onClickCountUp = (): void => {
this.setState({
// 스테이트가 객체니까 중괄호 쓰는 거 Component에서 셋스테이트를 자체적으로 지원!!
count: 1,
});
};
onClickMove = (): void => {
void Router.push("/"); // 안기달릴거면 void
};
render(): JSX.Element {
return (
<>
<div>{this.state.count}</div>
<button onClick={this.onClickCountUp}>카운트 올리기!!</button>
<button onClick={this.onClickMove}>나가기!!</button>
</>
);
}
}
출처: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
리액트 생명주기의 자세한 과정이다!!
먼저 컴포넌트가 생성될 때 constructor인 생성자 메서드가 먼저 실행이 된다.
render는 컴포넌트를 렌더링하는 메서드이다!
componentDidMount는 렌더링이 끝나고 호출되는 메서드이다!
즉 렌더링 이후에 만들어진 페이지가 화면에 보여주고 나서 호출되는 메서드인 것이다!
componentDidUpdate는 리렌더링이 끝나고 화면에 모든 변화가 나타나고 나서 호출 되는 메서드이다!
componentWillUnmount는 컴포넌트가 화면에 사라지기 전에 호출되는 메서드이다!
즉 우리가 다음 페이지로 갔을 때 호출 되는 페이지이다!