React hooks清除定时器并验证效果
目录结构
如下所示:

useTime hook
// src/hooks/common.ts
import { useEffect, useState } from "react";
export function useTime() {
const [time, setTime] = useState<Date>(() => new Date())
useEffect(() => {
const id: NodeJS.Timer = setInterval(() => {
setTime(new Date())
}, 1000)
return () => {
console.log('组件销毁清除定时器');
clearInterval(id)
}
}, [])
console.log('返回时间')
return time
}
Clock.tsx使用useTime hook
// src/test/Clock.tsx
import React from 'react';
import { useTime } from '@/hooks/common';
function Clock() {
const time = useTime()
return (
<h1>{time.toLocaleTimeString()}</h1>
);
}
export default Clock;
App.tsx显示Clock组件
// src/App.tsx
import React, { useState } from 'react';
import Clock from './test/Clock'
import './App.css';
function App() {
const [show, setShow] = useState<boolean>(true)
return (
<div className="App">
<button onClick={() => setShow(!show)}>{show ? '隐藏' : '显示'}</button>
{show && <Clock />}
</div>
);
}
export default App;
显示时间(开启定时器)

隐藏时间(清除定时器)

总结
React hook启用定时器后,在组件销毁时清除定时器
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
参考:
- 我尝试将 state 设置为一个函数,但它却被调用了
- Clear a timeout or an interval in React with hooks
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
















暂无评论内容