从API加载数据时Lottie-web动画加载状态下消失问题
解决API加载数据时Lottie-web动画消失的问题
问题分析
你的Lottie动画在API加载数据时消失,大概率是因为:
- 组件在API请求过程中发生重渲染,但原代码未保存Lottie实例引用,也未在组件卸载时清理实例,导致动画实例丢失
- 承载动画的容器元素可能因父组件加载状态切换被重新创建或隐藏
解决方案
通过以下步骤修复:
- 保存Lottie实例引用:用ref存储动画实例,确保组件重渲染时能访问到已有实例
- 管理实例生命周期:组件卸载时调用
destroy()清理实例,避免内存泄漏 - 防止不必要重渲染:用
React.memo包裹组件,减少父组件状态变化引发的无意义重渲染 - 处理props更新:当height/width等props变化时,重新初始化动画适配新尺寸
修正后的代码
import { Box } from '@mui/material'; import Lottie from 'lottie-web'; import React, { useEffect, useRef, memo } from 'react'; import notFoundLoadingAnimation from "../../../images/lotiieforNotFoundBaseRoute.json"; const BaseNotFoundLottieLoader = memo((props) => { const { height, width } = props; const animeContainerRef = useRef(null); const lottieInstanceRef = useRef(null); useEffect(() => { // 先销毁已有实例,避免重复初始化 if (lottieInstanceRef.current) { lottieInstanceRef.current.destroy(); } // 初始化新动画实例 if (animeContainerRef.current) { lottieInstanceRef.current = Lottie.loadAnimation({ container: animeContainerRef.current, renderer: "svg", loop: true, autoplay: true, animationData: notFoundLoadingAnimation, }); } // 组件卸载时清理实例 return () => { if (lottieInstanceRef.current) { lottieInstanceRef.current.destroy(); } }; }, [height, width]); // 尺寸变化时重新初始化 return ( <Box sx={{ display: 'flex', justifyContent: "center", alignItems: 'center' }}> <Box data-testid="not-found-animation" className="full-width-height container" style={{ height: height, width: width }} ref={animeContainerRef} ></Box> </Box> ); }); export default BaseNotFoundLottieLoader;
关键修改说明
- 新增
lottieInstanceRef存储动画实例,便于后续操作和清理 - 在
useEffect中先销毁旧实例再创建新实例,避免重复渲染冲突 - 添加卸载清理函数,防止内存泄漏
- 用
React.memo包裹组件,减少不必要的重渲染 - 将
height和width加入依赖数组,确保尺寸变化时动画能适配更新
内容的提问来源于stack exchange,提问作者Feroj
相关产品推荐
相关产品推荐

