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

react-ticker实现跑马灯报Maximum update depth exceeded错误咨询

问题描述

控制台抛出运行时错误:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.

业务场景为实现类似Instagram Reels、YouTube Shorts、TikTok的页脚跑马灯效果,引入react-ticker组件实现视频播放时文字从左到右持续滚动的功能,实际运行时跑马灯仅正常生效一次,就触发上述报错。
原始问题代码如下:

import React,{useEffect} from 'react';
import '../VideoFooter.css';
import disc from './static/disc.png';
import MusicNoteIcon from '@material-ui/icons/MusicNote';
import Ticker from 'react-ticker'

const VideoFooter = () => {
  return (
    <div className='videoFooter'>
      <div className="videoFooter_text">
        <h3>@priyansh21</h3>
        <p>Mindset is key to success</p>
        <div className="video_footer_ticker">
          <MusicNoteIcon className='video_footer_icon'/>
          <Ticker mode='smooth'>
             {({index}) => (
               <>
                  <p>This is the Headline of element #!</p>
               </>
             )}
          </Ticker>
        </div>
      </div>
      <img className='videoFooter_record' src={disc} alt="" />
    </div>
  )
}

export default VideoFooter;
问题原因

报错本质是组件进入了无限重渲染循环:react-ticker的render prop每次组件渲染时都会返回新创建的Fragment和p标签引用,旧版本react-ticker内部的props比对逻辑会将新的元素引用判定为props更新,触发自身重渲染,重渲染过程又会重新调用render prop生成新元素,循环往复直到触发React的更新深度上限保护,抛出错误。

修复方案

按优先级选择以下任意一种方案即可解决问题:

  • 固定滚动内容的引用:将Ticker内部渲染的滚动内容抽离到组件外部定义,避免每次渲染生成新的元素引用,修改后的代码如下:
import React from 'react';
import '../VideoFooter.css';
import disc from './static/disc.png';
import MusicNoteIcon from '@material-ui/icons/MusicNote';
import Ticker from 'react-ticker'

// 滚动内容抽离到组件外,引用固定不会随渲染变化
const ScrollText = () => <p>This is the Headline of element #!</p>

const VideoFooter = () => {
  return (
    <div className='videoFooter'>
      <div className="videoFooter_text">
        <h3>@priyansh21</h3>
        <p>Mindset is key to success</p>
        <div className="video_footer_ticker">
          <MusicNoteIcon className='video_footer_icon'/>
          <Ticker mode='smooth'>
            {() => <ScrollText />}
          </Ticker>
        </div>
      </div>
      <img className='videoFooter_record' src={disc} alt="rotating disc" />
    </div>
  )
}

export default VideoFooter;
  • 升级依赖版本:如果抽离内容后仍有报错,说明当前安装的react-ticker版本存在未修复的重渲染bug,执行以下命令升级到最新稳定版即可:
    npm install react-ticker@latest
  • 临时兼容方案:如果暂时无法修改依赖版本,可以给Ticker组件添加固定key值,强制组件仅在首次挂载时初始化,跳过后续无效的props更新比对:
    <Ticker mode='smooth' key="video-footer-ticker">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:09:23