我正在阅读官方React网站上的教程。在有关生命周期方法的示例中,在componentDidMount方法下,将timerID设置为setInterval函数。
我的问题是,即使timerID已初始化,也从未在整个应用程序中调用过,在不显式调用应用程序中任何地方的timerID的情况下,应用程序如何工作。这是下面的代码。
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>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('root') );
this.timerID是一个非零的数字值,它标识对的调用所创建的计时器setInterval()。该值可以传递clearInterval给清除计时器。
this.timerID
setInterval()
clearInterval
所以当在componentDidMount中调用setInterval时
componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); }
您要在安装组件后执行tick()功能every 1 sec a。现在,当您导航到另一个组件并且当前组件已卸载时,如果 不清除 对tick()函数 的间隔 调用,它将继续执行。
tick()
every 1 sec a
因此,在该componentWillUnmount函数中,将清除计时器,该计时器由setInterval存储在其中的返回数字值标识this.timerID
componentWillUnmount
setInterval
componentWillUnmount() { clearInterval(this.timerID); }
因此,React文档中提供的完整代码是