ComponentのLifecycle
ReactのComponentは生まれてから死ぬ(破棄される)までの間にたくさんのイベントが用意されており、それらのタイミングで特定のメソッドを実行してくれる機能を自由に使用することができます。
現在時間を表示するComponent その3
今回はReactの公式ドキュメントのソースを参考にしながら、前回まで作成してきたJustnow
Componentを時間が経過するごとに表示も変更するようにしてみたいと思います。
サンプル
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Justnow3</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Justnow extends React.Component {
constructor(props) {
super(props);
this.state = {
now: new Date()
};
}
/**
* Lifecycle: ComponentがDOMツリーに加わった際の処理
*/
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
/**
* Lifecycle: ComponentがDOMツリーから削除される際の処理
*/
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
now: new Date()
});
}
render() {
let now = this.state.now;
let now_date = [now.getFullYear(), now.getMonth()+1, now.getDate()].join('-');
let now_time = [now.getHours(), now.getMinutes(), now.getSeconds()].join(':');
return <h1>{now_date} {now_time}</h1>;
}
}
ReactDOM.render(
<Justnow />,
document.getElementById('root')
);
</script>
</body>
</html>
以下のページにあるサンプルコードを参考にしています。