javascript reactJS 中的 setTimeout 和 clearTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49085450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:24:52  来源:igfitidea点击:

setTimeout and clearTimeout in reactJS

javascriptreactjs

提问by semosem

I am trying to create a greeting UI that fades out before displaying main content.The desired effect can be found HERE

我正在尝试创建一个在显示主要内容之前淡出的问候语 UI。可以在此处找到所需的效果

When a certain scroll input, say 100px from the top, is reached

当达到某个滚动输入时,例如距顶部 100 像素

  1. Greeting appears for 5seconds and fades out
  2. Main content waits until greeting fades out and gets displayed.
  1. 问候语出现 5 秒然后淡出
  2. 主要内容等待问候语淡出并显示。

I achieved this effect with setTimeout but I now want to know how to set clearTimeout properly.

我使用 setTimeout 实现了这种效果,但我现在想知道如何正确设置 clearTimeout。

Here is my code

这是我的代码

componentDidMount() {
    window.addEventListener(
      "wheel",
      () => requestAnimationFrame(this.handleScroll.bind(this)),
      false
    );
  }

handleScroll(e){  
    const scrolltop = window.scrollY; 
    scrolltop > 120 ? this.showGreeting().bind(this):null
  }

showGreeting(){
    this.setState({
      greetingDisplay:true,
    })
    const timer = setTimeout(this.showContent.bind(this),5000);
  } 

showContent(){

    this.setState({
      greetingDisplay:false,
      contentDisplay:1,
   })
  //How do I clear the timer here? 
}
  • Hereis my attempt, Codepen
  • 是我的尝试,Codepen

回答by RIYAJ KHAN

In showGreeting,you are setting timeout and storing it in local constvaribale.Instead bind it to component instance i.e. this.

在中showGreeting,您正在设置超时并将其存储在local const变量中。而是将其绑定到组件实例,即this

constructor(){
     this.timer = null;
      //............rest
  }

showGreeting(){
    this.setState({
      greetingDisplay:true,
    })
    this.timer=setTimeout(this.showContent.bind(this),3000);
    ^^^^^^^^^^^
  } 

When showContentis called state is updated which will trigger renderand then componentDidUpdatelifecycle.

何时showContent被调用状态被更新,这将触发render然后componentDidUpdate生命周期。

In the componentDidUpdate, use this.timerto clear timeout.

在 中componentDidUpdate,用于this.timer清除超时。

componentDidUpdate{
   clearTimeout(this.timer);
}

回答by Roman

You can easily use ES6 arrow functions without side effects like this:

您可以轻松使用 ES6 箭头函数,而不会产生这样的副作用:

showContent = () => {
   this.setState({
      greetingDisplay:false,
      contentDisplay:1,
   }); 
}

showGreeting = () => {
    this.setState({
      greetingDisplay:true,
    });
    setTimeout( () => this.showContent, 3000 );
}