每当我向后导航时,都会调用useeEffect中的React settimeout

问题描述

我正在尝试在setTimeout和useEffect中更改元素的样式。

这是代码的样子

enter length of string
3|   //after,nextInt() when i=0,since the cursor is not the first,it breaks the line,a[0] = "n" 
enter string values
|one //when  i=1,since it's the firstit gives chance for input,and stores to a[1]
|two  //when  i=1,and stores to a[1]
     //a[0] is displayed
one  //a[1] is displayed
two  //a[2] is displayed

我发现渲染主页后,如果我导航到其他页面并返回到主页,将再次调用changesstyles1()并再次运行动画。从其他页面导航回到主页时,应该怎么做以避免再次调用setTimeout()。

您会发现,如果我从首页导航到其他页面然后返回首页,则changeStyle2不会再显示动画。这就是我想要的效果

我的网站托管在netlify上 我在codepen

上的代码

解决方法

我将从父级组件进行管理。

让我们假设以下组件树:

  • 应用
    • 首页
    • 第1页

在应用中:

const [isFirstMount,setFirstMount] = useState(true);
//...
return(
  <Home ...props changeStyle={isFirstMount} onStyleChanged={() => 
       setFirstMount(false)}/>
  //...
)
 

在家中:

if (props.changeStyle) {
  let pnt = setTimeout(()=>{
    // change styles  for 'frontenddevelopment'
    changeStyles1();
    onStyleChanged()
    clearTimeout(pnt);
   },1000)
}
,

您需要清除计时器,否则,您的代码可能会遇到不利的副作用。

useEffect(()=>{
    const timer = setTimeout(()=>{
        // change styles  for 'frontenddevelopment'
        changeStyles1();
    },1000)

    // changeStyles for 'i love frontend'
    changeStyles2()
    
    //clear the timer
    return () => clearTimeout(timer);

},[]);

有关更多信息,请参见此link