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

如何在React中使用setInterval()?——React可运行时钟组件实现求助

Fixing Your React Clock with setInterval

Got it, let's get your clock updating every second properly! The issue with your current code is two-fold:

  • You're only calculating the time once when the component renders, not triggering re-renders to refresh it
  • Putting setInterval directly in the render method would create a new timer every time the component re-renders, which is a memory leak waiting to happen

Here's the correct approach using React class component lifecycle methods:

Step-by-Step Explanation

  1. Store the current time in component state: React re-renders components when state or props change, so we need to hold the time in state to trigger updates.
  2. Set up the timer in componentDidMount: This lifecycle method runs once after the component mounts, making it the perfect spot to start our interval.
  3. Clear the timer in componentWillUnmount: Always clean up timers when the component unmounts to avoid lingering background processes.
  4. Update state in the tick method: Changing state will tell React to re-render the component with the latest time.

Modified Code

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

class App extends React.Component {
  // Initialize state with the current time
  state = {
    currentTime: new Date().toLocaleTimeString()
  };

  componentDidMount() {
    // Set up the interval to call tick every 1000ms (1 second)
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    // Clear the interval when the component unmounts
    clearInterval(this.timerID);
  }

  tick() {
    // Update state with the new time, triggering a re-render
    this.setState({
      currentTime: new Date().toLocaleTimeString()
    });
  }

  render() {
    // Display the time from state
    return <h1>{this.state.currentTime}</h1>;
  }
}

export default App;

Key Notes

  • We assign the interval ID to this.timerID so we can reference it later to clear the timer.
  • Using an arrow function in setInterval (() => this.tick()) ensures that this refers to the component instance when tick is called.
  • If you ever want to switch to functional components (the modern React standard), you could use the useState and useEffect hooks instead—but this keeps things consistent with your original class component setup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:17:37