如何结合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.
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
numberintothis.stateensures every update triggers a component re-render, so the UI always shows the latest value. - Functional
setState: UsingprevStateguarantees 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:
- On load, the component shows
33. - Each button click decreases the number by 1 until it reaches
0. - Clicking the button when the number is
0resets it back to33, ready to count down again.
内容的提问来源于stack exchange,提问作者selcukctn

