ale*_*s84 1 javascript onclick intervals reactjs
我正在用 React 构建一个小游戏,并准备在其中包含一个倒计时器。
有很多关于如何使用 React 创建计时器或倒计时器的教程(包括 React 官方文档中的教程)。然而,它们都使用componentDidMount和componentWillUnmount生命周期方法来设置和分别清除间隔。
这工作正常,但计时器在组件安装时开始计时。我想要一个在单击时开始计数的计时器。
实现这种行为的适当的生命周期方法是什么?我已经尝试过了componentWillUpdate,componentDidUpdate但没有效果。
我的第一个想法是使用 gameOn 状态属性,以便仅在游戏开启时(即按下开始按钮)才激活计时器,但这不起作用,因为(我猜)我将 gameOn 设置为 true,很久之后组件 didMount。
我还尝试在 Timer 组件上移动这两种方法以及适当的状态 ({secondsElapsed: 0}),因为 Timer 是一个单独的组件,通过 props 与其父组件进行通信。这也没有运气。
最后,我尝试设置this.interval = null;构造函数,但这对计时器的运行方式没有任何影响。
我认为问题的根源是生命周期方法,因为这些方法控制何时调用 setInterval 和clearInterval。所以我的问题是这样的:
我应该使用哪些其他生命周期方法组合来实现我所追求的行为?
任何精通的建议将不胜感激。
如果您能清楚地解释为什么以及何时应该this.interval = null;在构造函数中声明,那就加分了。
对于我到目前为止所拥有的示例,基本上可以看看“有状态组件”
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>
}
Run Code Online (Sandbox Code Playgroud)