首页 > 解决方案 > Display updated time each seconds in react function

问题描述

It must be a function, it can't be a class (class is able to do it in the componentDidMount with setInterval)

I set up something like this

function DisplayTime() {
  let time = new Date().getTime();
  setInterval(() => {
    time = new Date().getTime();
  }, 1000);
  return time;
}
ReactDOM.render(<DisplayTime />, document.getElementById('root'))

The problem is function can run only once, so the time won't able to get update. Something like setInterval(() => {ReactDOM.render(...), ...}) low efficient, which is not acceptable.

Any idea?

===
useState is advanced solution, any solution without using most recent version of React?

标签: javascriptreactjs

解决方案


import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [time, setTime] = useState(new Date().getTime());
  setInterval(() => {
    setTime(new Date().getTime());
  }, 1000);
  return (
    <div className="App">
      <h1>{time}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

推荐阅读