组件未呈现为反应中的方面

component not render as aspected in react

我有一个 React 组件:

  const [countdown, setCountdown] = useState(getCountdown());

  const getCountdown = () => {
const timeRemaining = new Date(`2021-12-18`) - new Date();

let countdown = {};

if (timeRemaining > 0) {
  countdown = {
    Week: Math.floor(timeRemaining / (1000 * 60 * 60 * 24 * 7)),
    Days: Math.floor(timeRemaining / (1000 * 60 * 60 * 24)),
    Hours: Math.floor((timeRemaining / (1000 * 60 * 60)) % 24),
    Minutes: Math.floor((timeRemaining / 1000 / 60) % 60),
    Seconds: Math.floor((timeRemaining / 1000) % 60),
  };
}
return countdown;

};

  useEffect(() => {
setTimeout(() => {
  setCountdown(getCountdown());
}, 5000);

和return这个:

  return (
<>
  {Object.entries(countdown).forEach(([unit, value]) => {
    return (
      <p key={Math.random().toString(16)}>
        {console.log(value)}
        <strong>{value}</strong> {unit}
      </p>
    );
  })}
</>);

我不明白为什么我每 5 秒在控制台中看到一个新值,但 HTML 没有更新 :(

我必须更改代码的哪些部分?

非常感谢您的帮助

forEach 没有 return 任何东西,而是使用 map

Object.entries(countdown).map(...)

import { useState, useEffect } from "react";

export default function App() {
    

    const getCountdown = () => {
        const timeRemaining = new Date(`2021-12-18`) - new Date();

        let countdown = {};

        if (timeRemaining > 0) {
            countdown = {
                Week: Math.floor(timeRemaining / (1000 * 60 * 60 * 24 * 7)),
                Days: Math.floor(timeRemaining / (1000 * 60 * 60 * 24)),
                Hours: Math.floor((timeRemaining / (1000 * 60 * 60)) % 24),
                Minutes: Math.floor((timeRemaining / 1000 / 60) % 60),
                Seconds: Math.floor((timeRemaining / 1000) % 60)
            };
        }
        return countdown;
  };
  
  const [countdown, setCountdown] = useState(getCountdown());

    useEffect(() => {
        setTimeout(() => {
            setCountdown(getCountdown());
        }, 5000);
    });

    return (
        <>
            {Object.entries(countdown).map(([unit, value]) => {
                return (
                    <p key={Math.random().toString(16)}>
                        {console.log(value)}
                        <strong>{value}</strong> {unit}
                    </p>
                );
            })}
        </>
    );
}

代码沙箱 => https://codesandbox.io/s/nostalgic-panini-kgk4j?file=/src/App.js