【问题标题】:I am not able to set interval in my react app我无法在我的反应应用程序中设置间隔
【发布时间】:2026-02-10 09:50:01
【问题描述】:

这是我的 showdate.js - >

import React, { Component } from "react";

class Showdate extends Component {
    componentWillMount() {
        setInterval(1000);
    }

    render() {
        return (
            <div>
                <h1>Welcome to GeeksforGeeks!</h1>
                <h2>{new Date().toLocaleTimeString()}</h2>
            </div>
        );
    }
}

export default Showdate;

并通过 index.js 渲染为 ->

import React from "react";
import ReactDOM from "react-dom";
import Showdate from "./showDate";
const rootElement4 = document.getElementById("root4");
console.log(<Showdate />);
ReactDOM.render(<Showdate />, rootElement4);

时间正在显示,但它没有刷新一秒,因为它应该符合 setinterval(1000)

【问题讨论】:

  • setInterval() 采用您未提供的回调函数。我建议您阅读文档以了解如何正确使用它。
  • 你使用setInterval的方式不正确。
  • 嗨@muralcode,最好更详细地描述您希望通过这段代码实现的目标,以便社区可以帮助您

标签: javascript reactjs


【解决方案1】:

你必须这样做:

constructor(props){
super(props);
  this.state = {
       myTime: new Date() //Initialize your state
    }
}
componentDidMount() { //Use componentDidMount instead of componentWillMount

    this.myInterval = setInterval(()=>this.tick(), 1000); //Provide a callback to setInterval
}
tick(){

  this.setState({myTime: new Date()})
}


 componentWillUnmount() {
    clearInterval(this.myInterval); //You must clear interval when the component is unmounted; otherwise it could lead to memory leakage 
  }

然后在你的 JSX 中使用 myTime &lt;h2&gt;{this.state.myTime.toLocaleTimeString()}&lt;/h2&gt;

【讨论】:

    【解决方案2】:

    你可以这样做:

    this.timerChronoId = setInterval(() => {
                    this.setState({
                        time: (this.state.time + 1)
                    });
                }, 1000);
    

    您可以使用 this.timerChronoId 来暂停计时器,方法是调用:

    clearInterval(this.timerChronoId);
    

    【讨论】:

      【解决方案3】:

      函数setInterval 正在接受回调函数和超时。因此,您必须按如下方式实现它。另外,您应该在卸载组件之前清除间隔。

          import React, { Component } from "react";
      
          class Showdate extends Component {
              constructor(props) {
                super(props);
                this.state = { date: new Date() }
              }
      
              componentDidMount() {
                this.timer = setInterval(() => this.tick(), 1000)
              }
      
              componentWillUnmount() {
                clearInterval(this.timer)
              }
      
              tick() {
                this.setState({ date: new Date() })
              }
      
              render() {
                  return (
                      <div>
                          <h1>Welcome to GeeksforGeeks!</h1>
                          <h2>{this.state.date.toLocaleTimeString()}</h2>
                      </div>
                  );
              }
          }
      
          export default Showdate;
      

      【讨论】:

        最近更新 更多