react在哪个生命周期调用定时器,何时销毁?
文章目录
之前的文章中,简单介绍过vue生命周期里面清除定时器的生命周期,今天看了react官方文档,上面说componentDidMount()方法会在组件已经被渲染到 DOM 中后运行,所以最好在这里设置计时器:
componentDidMount() {
timer = setInterval(() => {
this.setState(() => ({
count: --this.state.count,
}), () => {
if (this.state.count < 1) {
clearInterval(timer);
this.props.history.push("/main/home");
}
});
}, 1000)
}
通过自己试验,验证官方文档说的在生命周期方法中清除计时器
componentWillUnmount() {
clearInterval(timer);
}
ok了

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论