You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React数组打字机循环效果问题:首词不重复+出现undefined

问题修复:打字机循环输出异常

问题原因

  1. 数组边界判断错误:你的words数组长度为3(索引0、1、2),但代码中判断a > 3才重置索引,导致a递增到3时,words[3]不存在,返回undefined,进而输出"undefined"。
  2. 赋值顺序错误:先给txt赋值再重置索引,导致已经取到了undefined的数组元素。

修复步骤

  • 将索引重置条件改为a >= words.length,匹配数组实际长度。
  • 调整顺序:先判断并重置索引,再给txt赋值,避免取到不存在的数组元素。
  • (可选优化)将全局变量替换为React的useRef,符合组件状态管理规范,避免全局变量带来的潜在问题。

修复后的代码

const { useEffect, useRef } = React;

const words = ["Business", "Company", "Startup"];

function Home() {
  // 使用useRef保存状态,替代全局变量
  const iRef = useRef(0);
  const aRef = useRef(0);
  const txtRef = useRef(words[0]);
  const speed = 1100;
  const loop = true;

  const typeWriter = (headerMessage) => {
    if (iRef.current < txtRef.current.length) {
      headerMessage.innerHTML += txtRef.current.charAt(iRef.current);
      iRef.current++;
      setTimeout(() => typeWriter(headerMessage), speed);
    } else if (loop) {
      clearText(headerMessage);
    }
  };

  const clearText = (headerMessage) => {
    headerMessage.innerHTML = "";
    iRef.current = 0;
    aRef.current++;
    // 先判断索引是否超出数组长度,再重置
    if (aRef.current >= words.length) {
      aRef.current = 0;
    }
    // 重置后再赋值txt
    txtRef.current = words[aRef.current];
    setTimeout(() => {
      typeWriter(headerMessage);
    }, 2000);
  };

  useEffect(() => {
    const headerMessage = document.getElementById("header-message");
    if (headerMessage) {
      typeWriter(headerMessage);
    }
  }, []);

  return (
    <main>
      <section>
        <section>
          <div>Let Us Help Grow Your<p id="header-message"></p>.</div>
        </section>
        <section></section>
      </section>
    </main>
  );
}

ReactDOM.createRoot(document.body).render(<Home />);

关键修改点说明

  • 用useRef替代全局变量i、a、txt,确保状态被组件独立持有,避免全局污染。
  • 在clearText中先检查aRef.current是否超出数组长度,重置后再给txtRef.current赋值,彻底避免undefined的出现。
  • 移除了不必要的模板字符串${words[a]},直接使用words[aRef.current]即可。

内容的提问来源于stack exchange,提问作者Burner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:20:18