reactjs - React hook setState、setTimeout 内存泄漏
问题描述
import React, { useState, useEffect, useRef } from 'react';
import styles from './TextAnimation.module.scss';
const TextAnimation = () => {
const [typedText, setTypedText] = useState([
"Welcome to Byc",
"Change your Life"
]);
const [value, setValue] = useState();
const [inType, setInType] = useState(false);
let attachClasses = [styles.Blink];
if(inType) {
attachClasses.push(styles.Typing)
}
const typingDelay = 200;
const erasingDelay = 100;
const newTextDelay = 5000;
let textArrayIndex = 0;
let charIndex = 0;
const type = () => {
if(charIndex < typedText[textArrayIndex].length + 1) {
setValue(typedText[textArrayIndex].substring(0, charIndex));
charIndex ++;
setTime();
} else {
setInType(false);
setTimeout(erase, newTextDelay);
}
};
const setTime = () => {
setTimeout(type, typingDelay);
};
const erase = () => {
if(charIndex > 0) {
setValue(typedText[textArrayIndex].substring(0, charIndex - 1));
charIndex --;
setTimeout(erase, erasingDelay);
} else {
setInType(false);
textArrayIndex ++;
if(textArrayIndex >= typedText.length) {
textArrayIndex = 0;
}
setTimeout(type, newTextDelay - 3100);
}
};
useEffect(() => {
type();
}, [])
return (
<div className={styles.TextAnimation}>
<span className={styles.Text} >{value}</span><span className={attachClasses.join(' ')} > </span>
</div>
);
};
export default TextAnimation;
我正在尝试制作文字动画,但我收到了这样的消息......
警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。
我该如何解决?
解决方案
卸载组件时需要清除超时,否则卸载组件后可能会运行超时。
要做到这一点 :
- 将每个超时的返回值存储在某个 ref 的列表中(
React.useRef
例如) - 返回一个回调,
useEffect
用于清除超时clearTimeout(<return value of setTimeout>)
推荐阅读
- bash - 重复使用相同的 ssh 连接执行多个命令
- c# - 从 Azure AD B2C 获取用户信息并显示在 .NET Web 应用程序上
- arrays - MongoDB中GeoJSON的请求包络(最小/最大坐标)
- yaml - 添加/覆盖映射到 YAML 中的列表变量
- amazon-web-services - 如何将 AWS lambda 访问限制为仅一个角色
- angular - 在同一选项卡 PowerBi Embedded 报告中打开 Url
- android - 运行与终端分离的 AVD 模拟器
- pcl - 显示pcd文件头
- node.js - 节点 Cron 不在 Heroku 服务器上执行
- python-telegram-bot - 电报机器人不发送消息