我正在学习反应并且我的代码工作正常但我如何声明 currDate 一次以全局使用它以在 useState 中使用

I am learning react and my code is working fine but how can i declare currDate single time to use it globally to use in useState

如何全局声明 currDate 以在 useState 中使用它。以下代码工作正常,但希望提高效率。

有没有更好的方法来缩短代码?

import React, { useState } from "react";
        
const Clock = () => {
  const date = new Date();
  const currDate = date.toLocaleTimeString();
  const [currTime, updateTime] = useState(currDate);
  console.log(currDate);

   
  const timeHandler = () => {
    console.log(1);
    const date = new Date();
    const currDate = date.toLocaleTimeString();
    updateTime(currDate);
  };

  return (
    <>
      <h1> {currTime}</h1>
      <button type="button" onClick={timeHandler}>
        Updatetime
      </button>
    </>
  );
};

export default Clock;

如果您想缩短它,而不是重复从 toLocaleTimeString 获取 currDate 的行。您创建一个函数来执行此操作,并在任何需要的地方使用它。

示例 - 1

function getCurrDate() {
  return (new Date()).toLocaleTimeString()
}

const Clock = () => {
  const [currTime, updateTime] = useState(getCurrDate());

  return (
    <>
      <h1> {currTime}</h1>
      <button type="button" onClick={() => updateTime(getCurrDate())}>
        Updatetime
      </button>
    </>
  );
};

export default Clock;

示例 - 2

将最近的日期存储在状态中并从中导出 toLocaleTimeString()

const Clock = () => {
  const [currTime, updateTime] = useState(new Date());

  return (
    <>
      <h1> {currTime.toLocaleTimeString()}</h1>
      <button type="button" onClick={() => updateTime(new Date())}>
        Updatetime
      </button>
    </>
  );
};

export default Clock;

这样的事情对你有用吗?

  1 import React, { useState } from 'react';
  2 
  3 const getTime = () => {
  4   const date = new Date();
  5   const currDate = date.toLocaleTimeString();
  6 
  7   return currDate;
  8 };
  9 
 10 function Clock() {
 11   const [currTime, updateTime] = useState(getTime());
 12 
 13   const timeHandler = () => {
 14     updateTime(getTime());
 15   };
 16 
 17   return (
 18     <>
 19       <h1> {currTime}</h1>
 20       <button type="button" onClick={timeHandler}>
 21         Updatetime
 22       </button>
 23     </>
 24   );
 25 }
 26 
 27 export default Clock;