2017-04-20 111 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

所以简单的答案是:不。它只运行一次,当组件正在消失。 –