「React入門」componentDidMount()とcomponentWillUnmount()のサンプル
説明
componentWillUnmount() は、コンポーネントがアンマウントされて破棄される直前に呼び出されます。
componentDidMount() で作成された購読の解除など、このメソッドで必要なクリーンアップを実行します。
使用例
<script src="/react/16.4.0/umd/react.development.js"></script>
<script src="/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="cft"></div>
<script type="text/babel">
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!study skill in arkgame</h1>
<h2>時刻: {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('cft')
);
</script>