简体   繁体   English

setTimeout 后在 useEffect 钩子中丢失 ref

[英]Losing ref in useEffect hook after setTimeout

I'm trying to play an animation if requested by the prop after mounting the component.如果在安装组件后道具要求,我正在尝试播放动画。 But my ref seems to be getting reset to null after a setTimeout.但是我的 ref 似乎在 setTimeout 之后被重置为 null。

    let landingText = useRef(null);

    useEffect(() => {
    //ref shows div element here
        setTimeout(() => {
        //ref gets reset to null here
            if (!onShow) {
                playAnimation();
            }
        }, 1000);
    }, []);

I have fixed this by adding a new variable and passing it down -我通过添加一个新变量并将其传递下来来解决这个问题 -

    useEffect(() => {
        const el = landingText;
        setTimeout(() => {

But I was curious as to why this would be happening after a setTimeout.但是我很好奇为什么在 setTimeout 之后会发生这种情况。

发生这种情况的原因是在useEffect的第二个参数中, useEffect只需将空数组[]放在useEffect的第二个参数中,它应该添加onShow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM