如何在 return 中显示 useState 状态中的对象?

How do I display the objects inside a useState state in the return?

import React, { useState , useEffect} from 'react';

function Counter(){
    const targetDate = '1 Jan 2023';
    const target = new Date(targetDate);
    const currDate = new Date();

    const targetTime = target.getTime();
    const currDateTime = currDate.getTime();

    const time = targetTime - currDateTime;

    var seconds = Math.floor((time % (1000*60)) / 1000);
    var minutes = Math.floor((time % (1000*60 * 60)) / (1000 * 60));
    var hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (100 * 60 * 60));
    var days = Math.floor(time / (1000*60*60*24));

    const [ctime , setCTime] = useState({seconds , minutes , hours , days});

    useEffect(() =>{
        const interval = setInterval(() => setCTime(ctime) , 1000);
        return () => clearInterval(interval);
    })
    return(
        <div>
            <h1>Countdown</h1>
            {ctime}
        </div>
    )
}

export default Counter;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

这是我到目前为止的代码,我有所有需要显示的值,我想显示它们,但是由于我正在学习钩子以及如何使用它们,所以我无法弄清楚如何显示来自国家的价值。

我收到的错误是“错误:对象作为 React 子项无效(已找到:具有键 {seconds, minutes, hours, days}} 的对象)。如果您打算渲染子项集合,请改用数组。"

您正在渲染直接对象 ctime。您需要渲染属性。

return (
  <div>
    <h1>Countdown</h1>
    {ctime.seconds}
    {ctime.minutes}
    {ctime.hours}
    {ctime.days}
  </div>
);

我以为你想做一个倒数计时器。我用合适的反应代码写了类似的东西。

function Counter() {
  // initial state is 0 for all
  const [ctime, setCTime] = useState({
    seconds: 0,
    minutes: 0,
    hours: 0,
    days: 0,
  });

  // Do not use global variables if you don't need to
  const startCountDown = () => {
    const targetTime = new Date("1 Jan 2023").getTime();
    const currDateTime = new Date().getTime();
    const time = targetTime - currDateTime;

    const s = Math.floor((time % (1000 * 60)) / 1000);
    const m = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
    const h = Math.floor((time % (1000 * 60 * 60 * 24)) / (100 * 60 * 60));
    const d = Math.floor(time / (1000 * 60 * 60 * 24));

    setCTime({ seconds: s, minutes: m, hours: h, days: d });
  };

  useEffect(() => {
    const interval = setInterval(() => startCountDown(), 1000);
    return () => clearInterval(interval);
  });

  return (
    <div>
      <h1>Countdown</h1>
      <div>
        {ctime.days}:{ctime.hours}:{ctime.minutes}:{ctime.seconds}
      </div>
    </div>
  );
}