【发布时间】:2021-08-06 16:14:36
【问题描述】:
我有几个问题想汇总一下。
- 点击另一个页面上的按钮后如何启动倒计时?
- 点击计时器后,如何防止在页面刷新时重置? (我找到了使用 cookie 等的示例,但我找不到将它们添加到下面代码中的方法)。
- 定时器只会在按下按钮时停止。
import React, { Component } from 'react'
class Timer extends Component {
state = {
minutes: 1,
seconds: 0,
}
componentDidMount() {
this.myInterval = setInterval(() => {
const { seconds, minutes } = this.state
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}))
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(this.myInterval)
} else {
this.setState(({ minutes }) => ({
minutes: minutes - 1,
seconds: 59
}))
}
}
}, 1000)
}
componentWillUnmount() {
clearInterval(this.myInterval)
}
render() {
const { minutes, seconds } = this.state
return (
<div>
{ minutes === 0 && seconds === 0
? <h1></h1>
: <h1>Timer is counting: {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
}
export default Timer
任何帮助将不胜感激。提前谢谢你:)
【问题讨论】:
-
所以你在页面 B 上,你按下一个按钮。并且在页面 A 中,触发了一个计时器?
-
使用redux,当按钮被点击时存储日期时间,当按钮被按下时以及任何你想要的计时器逻辑检查redux状态是否设置了日期时间然后启动计时器并通过比较按钮按下日期时间和计算经过的时间当前日期时间。
-
编写简单的浏览器扩展,即使对于初学者也很容易(很多教程)或使用像 Toggle 之类的东西(不是你要找的东西,但足够接近)。
-
@MarcCharpentier 是的!在页面 B 上,当您按下按钮时,按钮会将您带到页面 A,计时器开始倒计时。
标签: javascript reactjs react-native components