React——定时器在点击按钮时开始计时
React-- Timer begins counting seconds in the click of a button
我正在使用 React 构建一个小游戏,我准备在其中包含一个倒数计时器。
关于如何使用 React 创建计时器或倒数计时器的教程很多(包括 React 官方文档中的一个)。然而,它们都使用 componentDidMount
和 componentWillUnmount
生命周期方法来设置和分别清除间隔。
这工作正常,但计时器开始计算组件安装的时刻。我想要一个开始计算 onClick 的计时器。
实现这种行为的适当生命周期方法是什么?我已经尝试了 componentWillUpdate
和 componentDidUpdate
但没有效果。
我的第一个想法是使用 gameOn 状态 属性 以便仅在游戏开启时激活计时器(即已按下开始按钮)但这没有用,因为(我猜)我在组件 didMount 很久之后,我将 gameOn 设置为 true。
我还尝试在 Timer 组件上移动这两种方法以及适当的状态 ({secondsElapsed: 0}),因为 Timer 是一个单独的组件,通过 props 与其父组件通信。这也没有运气。
最后,我尝试在我的构造函数上设置 this.interval = null;
,但这对 Timer 的运行方式没有影响。
我认为问题的根源在于生命周期方法,因为这些方法控制何时调用 setInterval 和 clearInterval。所以我的问题是:
我应该使用其他哪些生命周期方法组合来实现我所追求的行为?
任何精通的建议将不胜感激。
如果你能清楚地解释我为什么以及什么时候应该在我的构造函数上声明 this.interval = null;
加分。
关于我目前所拥有的示例,基本上看一下“A Stateful Component”
componentWillUnmount() {
clearInterval(this.interval); // Always clean up before unmounting
}
render(){
<div>
<button
onClick={() => { this.interval = setInterval(() => {
// Do something here e.g. increment the time
// NOTE: `this` keyword here refers to the component itself
}, 1000); }}>
Start
</button>
</div>
}
我正在使用 React 构建一个小游戏,我准备在其中包含一个倒数计时器。
关于如何使用 React 创建计时器或倒数计时器的教程很多(包括 React 官方文档中的一个)。然而,它们都使用 componentDidMount
和 componentWillUnmount
生命周期方法来设置和分别清除间隔。
这工作正常,但计时器开始计算组件安装的时刻。我想要一个开始计算 onClick 的计时器。
实现这种行为的适当生命周期方法是什么?我已经尝试了 componentWillUpdate
和 componentDidUpdate
但没有效果。
我的第一个想法是使用 gameOn 状态 属性 以便仅在游戏开启时激活计时器(即已按下开始按钮)但这没有用,因为(我猜)我在组件 didMount 很久之后,我将 gameOn 设置为 true。
我还尝试在 Timer 组件上移动这两种方法以及适当的状态 ({secondsElapsed: 0}),因为 Timer 是一个单独的组件,通过 props 与其父组件通信。这也没有运气。
最后,我尝试在我的构造函数上设置 this.interval = null;
,但这对 Timer 的运行方式没有影响。
我认为问题的根源在于生命周期方法,因为这些方法控制何时调用 setInterval 和 clearInterval。所以我的问题是:
我应该使用其他哪些生命周期方法组合来实现我所追求的行为?
任何精通的建议将不胜感激。
如果你能清楚地解释我为什么以及什么时候应该在我的构造函数上声明 this.interval = null;
加分。
关于我目前所拥有的示例,基本上看一下“A Stateful Component”
componentWillUnmount() {
clearInterval(this.interval); // Always clean up before unmounting
}
render(){
<div>
<button
onClick={() => { this.interval = setInterval(() => {
// Do something here e.g. increment the time
// NOTE: `this` keyword here refers to the component itself
}, 1000); }}>
Start
</button>
</div>
}