简体   繁体   English

当我更改其状态时,React 组件不会呈现

[英]React component doesn't render when I change its state

I am trying to make a clock feature on my React site, and I have written this code for the component:我正在尝试在我的 React 站点上创建一个时钟功能,并且我为该组件编写了以下代码:

import React, { Component } from "react";

class Clock extends Component {
  state = { time: "00:00" };

  getTime = () => {
    var d = new Date();
    var hours = d.getHours();
    var mins = d.getMinutes();
    var secs = d.getSeconds();
    if (mins < 10) {
      mins = "0" + mins;
    }
    if (secs < 10) {
      secs = "0" + secs;
    }
    let formatDate = hours + ":" + mins + ":" + secs;
    this.setState({ time: formatDate });
  };

  componentDidMount() {
    this.getTime();
    setInterval(this.getTime(), 1000);
  }

  render() {
    return (
      <div>
        <p className="Clock">{this.state.time}</p>
        <button onClick={this.getTime}>Refresh</button>
      </div>
    );
  }
}

export default Clock;

I am trying to make the time that this component displays update every second, and I thought that just using setState would re-render it.我试图让这个组件显示的时间每秒更新一次,我认为只使用setState会重新渲染它。 I then found out that I could put the code in a method, and then call this method inside of a setInterval in componentDidMount however neither of these methods worked.然后我发现我可以将代码放在一个方法中,然后在componentDidMountsetInterval中调用这个方法,但是这些方法都不起作用。

I am probably doing something dumb, but is there a simple way I can get this component to re-render itself every second?我可能正在做一些愚蠢的事情,但是有没有一种简单的方法可以让这个组件每秒重新渲染?

Try this:尝试这个:

 componentDidMount() {
  this.getTime();
  setInterval(this.getTime, 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM