在React Component中使用setInterval [英] Using setInterval in React Component
问题描述
我正在阅读官方反应网站上的教程。在关于生命周期方法的示例中,在componentDidMount方法下,将timerID设置为setInterval函数。
I was reading the tutorial on the official react website. In the example about life cycle methods, under the componentDidMount method, a timerID is set to the setInterval function.
我的问题是即使timerID已经初始化,它也从未在整个应用程序中调用过,如果没有在应用程序中的任何地方显式调用timerID,应用程序如何工作。以下是下面的代码。
My question is even though the timerID was initialized, it was never called throughout the application, how does the application work without explicitly calling timerID anywhere in the application. Here is the code below.
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
is a numeric, non-zero value which identifies the timer created by the call to setInterval()
; this value can be passed to clearInterval
to clear the timer.
所以在componentDidMount中调用setInterval时就像
So when calling the setInterval in componentDidMount like
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
你想要执行 tick()
函数每1秒一次
组件已安装。现在,当您导航到另一个组件并且当前组件已卸载时,如果您不清除间隔调用 tick()
函数,它将会继续执行。
you want to execute the tick()
function every 1 sec a
fter the component has mounted. Now when you navigate to another component and your current component has unmounted, if you do not clear the interval call to tick()
function, it will continue to be executed.
因此在 componentWillUnmount
函数中,您的计时器被清除,该计时器由返回的数值标识通过 setInterval
存储在 this.timerID
Hence in the componentWillUnmount
function you timer is cleared which is identified by the numeric value returned by setInterval
which is stored in this.timerID
componentWillUnmount() {
clearInterval(this.timerID);
}
所以React docs中提供的完整代码是
so the complete code as provided in the React docs is
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')
);
这篇关于在React Component中使用setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!