0

有人可以发现错误,UI 没有呈现,我尝试通过 formatTime作为依赖项传递给,useEffect但它的行为非常烦人。

观察:有时它在页面重新加载时起作用但有时它不重新呈现视图不一致

import React, { useState, useEffect, useCallback } from "react";
import "./styles.css";

export default function App() {
  let date = new Date();

  const formatTime = useCallback(() => {
    return (
      date.getHours().toString() +
      ":" +
      date.getMinutes().toString() +
      ":" +
      date.getSeconds().toString() +
      ":" +
      date.getMilliseconds().toString()
    );
  }, [date]);

  const [timer, setTimer] = useState(formatTime());

  useEffect(() => {
    let interval = setInterval(() => {
      setTimer(formatTime());
    });
    return () => {
      clearInterval(interval);
    };
  });

  return (
    <div className="App">
      <h3> Timer: {timer.toString()} </h3>
    </div>
  );
}
4

0 回答 0