React hooks 清除定时器并验证效果
目录结构如下 useTime hook Clock.tsx使用useTime hook App.tsx显示Clock组件
总结 参考
目录结构如下
useTime hook
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
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组件
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