React 应用程序中的倒计时似乎呈指数级倒计时



我正在尝试使用 React JS 制作一个简单的倒计时按钮。它几乎完成了,但是,当我希望它仅在单击按钮后开始倒计时时,它会立即倒计时。

默认值为 10。如果您不输入自己的值,大于 0,则它将从 10 开始倒计时。

下面是我的代码:

import React, {Component} from 'react';
import './app.css';
import { Form, FormControl, Button } from 'react-bootstrap';
class Countdown extends Component {
constructor(props){
super(props);
this.state={
time: ''
}
}
componentWillMount(){
this.setState({time: 10});
}
componentDidMount(){
setInterval(() => this.registerTime(this.state.time - 1), 1000);
}
registerTime(time){
if(time >= 0){
this.setState({time});
}
}
countdown(){
const textVal = document.getElementById('time-input').value;
if(isNaN(textVal) || textVal == '' || textVal == ' ' || textVal <= 0){
alert("Please enter a numeric value greater than 0!");
} else{
this.registerTime(textVal);
}
}
render(){
return(
<div className="app">
<h1>This is going to be a Countdown!</h1>
<div>{this.state.time}</div>
<Form inline>
<FormControl 
id="time-input"
placeholder="new time" 
onChange={event => {
if(event.target.value != '' && event.target.value != ' '){
this.setState({time: event.target.value});
}
}}
onKeyPress={event => {
if(event.key === 'Enter'){this.countdown();}
}}
/>
<Button onClick={event => this.countdown()} >Start</Button>
</Form>
</div>
);
}
}
export default Countdown;

挂载组件时,您已经立即开始间隔。我已经在codepen为您创建了一个工作演示。 https://codepen.io/RutulPatel7077/pen/yRpzVB

这可能与 componentDidMount 方法有关,其中 setInterval 每 1 秒调用一次 registerTime?

最新更新