博客 / 詳情

返回

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了

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.