You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合if语句与按钮实现从33倒计时到0后重置为33?

Hey there! Let's fix up your countdown component to work exactly how you want—counting down from 33 to 0, then resetting back to 33 once it hits 0. I'll walk you through the changes, including using an if statement for the reset logic, and fix a key React best practice issue in your original code.

Fixed React Countdown Component with Reset Logic

First, a quick note on your original code: storing the number value in a plain instance property (harrik) won't work for React updates. React only re-renders components when state or props change, so updating harrik.number won't make the UI show the new value. We'll move number into the component's state first.

Here's the updated code with the full countdown and reset logic:

import React, { PureComponent } from 'react';

export default class App extends PureComponent {
  constructor(props) {
    super(props);
    // Initialize state with our starting countdown value: 33
    this.state = {
      number: 33
    };
  }

  onPressDecrease = () => {
    // Use functional setState to safely access the latest state value
    this.setState(prevState => {
      // Check if we've reached 0
      if (prevState.number === 0) {
        // Reset back to 33 when we hit 0
        return { number: 33 };
      } else {
        // Otherwise, decrease the number by 1
        return { number: prevState.number - 1 };
      }
    });
  }

  render() {
    return (
      <div>
        {/* Display the current countdown number */}
        <h2>{this.state.number}</h2>
        {/* Button to trigger the countdown/reset */}
        <button onClick={this.onPressDecrease}>Count Down</button>
      </div>
    );
  }
}

Key Details Breakdown:

  • State instead of plain property: Moving number into this.state ensures every update triggers a component re-render, so the UI always shows the latest value.
  • Functional setState: Using prevState guarantees we're working with the most up-to-date state value—this is crucial when state changes depend on previous state.
  • If statement logic: The core of your requested functionality: when the number hits 0, clicking the button resets it to 33; otherwise, it counts down by 1 each click.

How It Runs:

  1. On load, the component shows 33.
  2. Each button click decreases the number by 1 until it reaches 0.
  3. Clicking the button when the number is 0 resets it back to 33, ready to count down again.

内容的提问来源于stack exchange,提问作者selcukctn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:02:53