我正在阅读react官方网站上的教程。在关于生命周期方法的示例中,在componentDidMount方法下,为setInterval函数设置了一个timerID。
我的问题是,即使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')
);
发布于 2017-07-18 13:31:19
this.timerID
是一个非零数值,用于标识通过调用setInterval()
创建的计时器;可以将该值传递给clearInterval
以清除计时器。
因此,在componentDidMount中调用setInterval时,如
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
您希望在挂载组件之后执行tick()
函数every 1 sec a
。现在,当您导航到另一个组件并且当前组件已卸载时,如果您没有清除对tick()
函数的间隔调用,它将继续执行。
因此,在componentWillUnmount
函数中,您的计时器将被清除,该值由存储在this.timerID
中的setInterval
返回的数值标识
componentWillUnmount() {
clearInterval(this.timerID);
}
因此,React文档中提供的完整代码是
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')
);
发布于 2017-07-18 13:45:09
这很简单。一旦React执行componentDidMount()生命周期方法,计时器就开始运行。
this.timerID = setInterval(
() => this.tick(),
1000
);
上面的计时器将一直运行,直到组件被卸载(根据您的代码)。您的代码以这种方式工作并不令人惊讶。
发布于 2018-10-11 19:34:12
在这个react文档中,它写道
我们将拆除componentWillUnmount()生命周期方法中的计时器
因此,在componentWillUnmount()
生命周期方法中将使用this.timerID
来停止计时器。
https://stackoverflow.com/questions/45158087
复制相似问题