2017-04-20 62 views
0

爲什麼他們在這裏使用componentWillUnmountclearInterval「componentWillUnmount」如何以清除間隔工作?

componentWillUnmount() { 
    clearInterval(this.timerID); 
    console.log("here"); //nothing happens 
} 

in this example at the official docs

爲什麼他們使用它,因爲這種方法不會被調用在這個週期,因此調用clearInterval不會每秒執行一次?這不是每秒都會有一個新的時間間隔發生的想法嗎?或者我誤解?

+0

我的回答有用嗎?如果是這樣,請隨時投票,如果它解決了您的問題,請點擊對勾。你也會得到一些代表點。 :-) –

回答

1

當組件卸載並從DOM中刪除時,我們不希望this.tick()再運行。 componentWillUnmount是爲了消除當它安裝先前設置的時間間隔:

componentDidMount() { 
    this.timerID = setInterval(
    () => this.tick(), 
     1000 
    ); 
    } 

componentWillUnmountcomponentDidMount最喜歡的生命週期方法來處理的東西是什麼陣營直接管理,但東西,仍然發生的部分外你的組件。

+0

我明白了,我不明白的是什麼時候該組件卸載?它是否每秒鐘卸載?如果是這樣的話,爲什麼不清除間隔並在它之後記錄線? –

+2

'componentWillUnmount'只在組件離開時卸載(卸載),所以'this.tick()'每1000毫秒運行一次,直到'componentWillUnmount'移除它爲止。然後滴答停止。示例中的組件在掛載(出現)時開始滴答滴答,並且在掛載(消失)時停止滴答滴答。請記住'clearInterval'是INSIDE'componentWillUnmount'。它在'componentWillUnmount'運行時運行,而不是相反。 –

+1

所以簡單的答案是:不。它只運行一次,當組件正在消失。 –