0
点赞
收藏
分享

微信扫一扫

vue 打包 插槽 inject reactive draggable 动画 foreach pinia状态管理

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;

显示时间(开启定时器)

在这里插入图片描述

隐藏时间(清除定时器)

在这里插入图片描述

总结

  1. React hook启用定时器后,在组件销毁时清除定时器

参考

  • 我尝试将 state 设置为一个函数,但它却被调用了
  • Clear a timeout or an interval in React with hooks
举报

相关推荐

0 条评论