在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。
比如,每当 Clock 组件第一次加载到 DOM 中,我们都想生成一个定时器,这在 React 中被称为【挂载】。
同样,每当 Clock 生成的 DOM 被移除时,我们也要清除定时器,这在 React 中称为【卸载】。
实现一个时间实时变化的实例:
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>现在是:{this.state.date.toLocaleTimeString()}</h2>
</div>
)
}
}