Отображение текущей даты и времени в React.js: методы и примеры

Чтобы отобразить текущую дату и время в приложении React.js, вы можете использовать объект JavaScript Dateвместе с управлением состоянием React. Вот несколько различных методов, которые вы можете использовать:

Метод 1: использование setInterval

import React, { useState, useEffect } from 'react';
const CurrentDateTime = () => {
  const [currentDateTime, setCurrentDateTime] = useState(new Date());
  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentDateTime(new Date());
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  return (
    <div>
      Current Date and Time: {currentDateTime.toString()}
    </div>
  );
};
export default CurrentDateTime;

Метод 2: использование setTimeout

import React, { useState, useEffect } from 'react';
const CurrentDateTime = () => {
  const [currentDateTime, setCurrentDateTime] = useState(new Date());
  useEffect(() => {
    const updateDateTime = () => {
      setCurrentDateTime(new Date());
      setTimeout(updateDateTime, 1000);
    };
    updateDateTime();
  }, []);
  return (
    <div>
      Current Date and Time: {currentDateTime.toString()}
    </div>
  );
};
export default CurrentDateTime;

Метод 3: использование requestAnimationFrame

import React, { useState, useEffect } from 'react';
const CurrentDateTime = () => {
  const [currentDateTime, setCurrentDateTime] = useState(new Date());
  useEffect(() => {
    const updateDateTime = () => {
      setCurrentDateTime(new Date());
      requestAnimationFrame(updateDateTime);
    };
    updateDateTime();
  }, []);
  return (
    <div>
      Current Date and Time: {currentDateTime.toString()}
    </div>
  );
};
export default CurrentDateTime;

Все эти методы используют перехватчик useEffectдля установки интервала или таймаута, который обновляет состояние текущей датой и временем каждую секунду. Затем дата и время отображаются в JSX компонента.