跳到主要内容

useClock

语法


定义 hook
import React, {useState, useEffect} from 'react';

const useClock = () => {
const [time, setTime] = useState<Date>(new Date());

useEffect(() => {
const timer = setInterval(() => {
setTime(new Date());
}, 1000);
return () => {
clearInterval(timer);
};
}, []);

return time;
};

export default useClock;
使用 hook
import React from 'react';
import useClock from './hooks/useClock';

function App() {
const time = useClock();
return (
<div>
<div>现在时间为: {time.toLocaleDateString()}</div>
</div>
);
}

export default App;