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启用定时器后,在组件销毁时清除定时器
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
参考:
发表评论