React hooks如何清除定时器并验证效果

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
© 版权声明
THE END
支持一下吧
点赞8 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容