1

如何全局声明 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;
4

2 回答 2

0

这样的事情对你有用吗?

  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;
于 2020-09-19T08:09:32.390 回答
0

如果您想让它简短,而不是重复currDatetoLocaleTimeString. 您创建一个执行此操作的函数,并在任何您想要的地方使用它。

示例 - 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;
于 2020-09-19T07:39:04.597 回答