React.js中如何让useState控制的DOM元素30秒后自动移除
实现方案
核心逻辑是在触发提示显示时启动30秒倒计时,到期自动更新控制显示的状态,同时补充定时器清理逻辑避免异常。
完整代码实现如下:
1. 状态与逻辑定义
import { useState, useRef, useEffect } from 'react'; // 组件内部逻辑 const [showComponent, setShowComponent] = useState(false); // 存储定时器ID,用于清理和避免重复计时 const timerRef = useRef(null); const toggleLogoutMessage = () => { // 每次点击先清空已存在的定时器,避免多次点击导致计时混乱 if (timerRef.current) { clearTimeout(timerRef.current); } const nextShowState = !showComponent; setShowComponent(nextShowState); // 仅当提示需要显示时,启动30秒自动关闭定时器 if (nextShowState) { timerRef.current = setTimeout(() => { setShowComponent(false); timerRef.current = null; }, 30 * 1000); } }; // 组件卸载时清理未执行的定时器,避免内存泄漏 useEffect(() => { return () => { if (timerRef.current) { clearTimeout(timerRef.current); } }; }, []);
2. 组件渲染部分(无需修改)
<div role="button" className="user-navigation--item" onClick={toggleLogoutMessage}> <i className="fas fa-sign-out-alt user--nav--icon"></i> {' Logout '} {showComponent && <h1>Do you really want to log out</h1>} </div>
逻辑说明
- 多次点击Logout按钮时,会重置倒计时,保证每次显示提示都会重新计算30秒的关闭时间
- 组件提前卸载时,会自动清空未执行的定时器,不会出现控制台警告或内存泄漏问题
- 30秒到期后showComponent自动变为false,对应的h1元素会直接从DOM树中移除
内容的提问来源于stack exchange,提问作者zain
相关产品推荐
相关产品推荐

