使用效果是重复Lottie动画
在这里学习反应,我只是试图展示洛蒂动画。似乎很简单,但是我在使用效果挂钩方面遇到了一些麻烦。我正在使用钩子在页面加载上渲染动画,但它会不断重复(有时是两次或更多)。我知道这是因为使用效率会不止一次发射,但我不确定如何处理。我只想在页面上一个动画。我该如何实现?
import React, { useEffect, useRef } from "react";
import "./index.scss";
import lottie from "lottie-web";
const Hero = () => {
const lottieContainer = useRef(null);
useEffect(() => {
lottie.loadAnimation({
container: lottieContainer.current,
renderer: "svg",
loop: true,
autoplay: true,
animationData: require("../../assets/Lottie/developer.json"),
});
}, []);
return (
<div className="hero">
<div ref={lottieContainer}></div>
</div>
);
};
export default Hero;
Learning React here, and I'm simply trying to display a lottie animation. Seems fairly straight-forward, but I'm having some trouble with the useEffect hook. I'm using the hook to render the animation on page load, but it keeps repeating itself (sometimes twice or more). I know this is because useEffect will fire more than once, but I'm not sure how to handle this. I just want one animation on the page. How can I achieve this?
import React, { useEffect, useRef } from "react";
import "./index.scss";
import lottie from "lottie-web";
const Hero = () => {
const lottieContainer = useRef(null);
useEffect(() => {
lottie.loadAnimation({
container: lottieContainer.current,
renderer: "svg",
loop: true,
autoplay: true,
animationData: require("../../assets/Lottie/developer.json"),
});
}, []);
return (
<div className="hero">
<div ref={lottieContainer}></div>
</div>
);
};
export default Hero;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为反应严格模式,它试图帮助您检测不需要的副作用并运行所有
使用效果
两次挂钩,因此您可以看到您忘记了一些东西。在这种情况下,您忘了添加清理功能,没有lottie
创建2个动画,而无需清理第一个动画。只需将其添加到您的代码中:codesandbox
It's because of React strict mode, it tries to help you to detect unwanted side effects and runs all
useEffect
hooks twice, so you could see that you forgot something. And in that case you forgot to add cleanup function, without itlottie
creates 2 animations without cleaning up the first one. Just add this to your code:Codesandbox
useffect
方法,当您编写时,它将在安装组件时执行内部函数,您的useffect
还可以,您的lottie config对象具有loop
重复动画的属性。你应该替换为useEffect
method as you have write it will execute the inside function when your component is mounted, youruseEffect
is ok, your lottie config object has aloop
property that repeat your animation. You should replace by