React打字动画组件仅渲染两次后停止的问题求助
React打字动画组件修复方案
问题根源
- 直接修改State原始对象:在
useEffect里直接给txt.current_text、txt.index赋值,违反了React的state不可变原则,React无法检测到这种修改。 - State更新引用未变:用
Object.assign(txt)返回的还是原对象的引用,React对比新旧state时会认为没有变化,不会触发组件重渲染,导致useEffect只执行两次就停了。 - Flasher组件Props接收错误:
Flasher(flash)里的flash是整个props对象,不是传入的布尔值,属于潜在bug。 - 未清理定时器:每次
useEffect执行都会新建定时器,旧的定时器没被清理,容易引发内存泄漏和逻辑混乱。
修复步骤
- 创建State副本更新:永远通过创建新对象的方式更新state,比如用扩展运算符
{...txt}或者Object.assign({}, txt),确保React能检测到变化。 - 添加useEffect依赖数组:给
useEffect加上[txt, speed]依赖,保证每次state或speed变化时,都能触发下一次打字逻辑。 - 清理定时器:在
useEffect的返回函数里清除定时器,避免内存泄漏。 - 修正Flasher组件Props:改成解构接收
{ flash },确保布尔值判断正确。
修复后的完整代码
import { useEffect, useState } from "react"; import parse from 'html-react-parser'; function randomIntFromInterval(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min) } function Flasher({ flash }) { // 修复props解构 const [flashval, updateFlash] = useState("<span>  </span>") useEffect(() => { if (!flash) return; const timer = setTimeout(() => { // 用函数式更新避免闭包问题 updateFlash(prev => prev === " |" ? "<span>  </span>" : " |"); }, 375); // 清理定时器 return () => clearTimeout(timer); }, [flash, flashval]); // 添加依赖数组 return (<>{parse(flashval)}</>) } export default function Typer({ text, transform, flash, speed = 1 }) { const [txt, updateTxt] = useState({ options: text.split("|"), index: 0, current_text: "" }); useEffect(() => { let min = 1, max = 4; const current_full_text = txt.options[txt.index]; // 创建新的state对象,不修改原对象 const newTxt = { ...txt }; newTxt.current_text = current_full_text.substring(0, newTxt.current_text.length + 1); if (newTxt.current_text === current_full_text) { newTxt.index++; if (newTxt.index > newTxt.options.length - 1) { newTxt.index = 0; newTxt.current_text = ""; min = 4; max = 10; } } const timer = setTimeout(() => { updateTxt(newTxt); }, randomIntFromInterval(min, max) * 100 * speed); // 清理定时器 return () => clearTimeout(timer); }, [txt, speed]); // 添加依赖数组 return (<span>{txt.current_text}<Flasher flash={flash}/></span>) }
关于useRef的疑问
不需要用useRef直接修改innerText,React的state机制完全能处理这个场景。直接操作DOM会绕过React的渲染流程,反而容易引发状态不一致问题,保持用state管理是更规范的做法。
内容的提问来源于stack exchange,提问作者Lewis Morris
相关产品推荐
相关产品推荐

