React App中的倒数似乎以指数形式倒数

时间:2018-10-16 13:22:36

标签: javascript reactjs components

我正在尝试使用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;

2 个答案:

答案 0 :(得分:1)

安装组件后,您马上就开始了间隔。我在click_button_in_section("Aggregated Price and Demand Data - Historical", "SA") click_button_in_section("Aggregated Price and Demand Data - Historical", "NSW") click_button_in_section("Aggregated Price and Demand Data - Current Month", "TAS") click_button_in_section("Aggregated Price and Demand Data - Current Month", "VIC") 中为您创建了一个有效的演示。 https://codepen.io/RutulPatel7077/pen/yRpzVB

答案 1 :(得分:0)

它可能与componentDidMount方法有关,该方法中setInterval每1秒在registerTime上调用一次?