: 매 중요한 순간마다, 컴포넌트는 새로 렌더링 된다.
그 중요한 순간들을 제어하기 위한 방법이다.
: 화면에 등장한 후
: 컴포넌트가 새로운 상태를 가지고 난 후
: 화면에서 사라지기 전
시계 만들기
1. componentDidMount를 활용하여 1초마다 tick함수를 작동하게 하였다.
2. componentWillInmount를 활용하여 시계가 작동하지 않도록 해주었다.
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<FormattedDate date={this.state.date} />
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);