Javascript reactJS中的setTimeout和clearTimeout

Javascript reactJS中的setTimeout和clearTimeout,javascript,reactjs,Javascript,Reactjs,我正在尝试创建一个在显示主要内容之前淡出的问候UI。可以找到想要的效果 当达到某个滚动输入时,例如从顶部开始的100px 问候语出现5秒钟后消失 主要内容等待问候语淡出并显示出来 我用setTimeout实现了这个效果,但我现在想知道如何正确设置clearTimeout 这是我的密码 componentDidMount() { window.addEventListener( "wheel", () => requestAnimationFrame(this

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

当达到某个滚动输入时,例如从顶部开始的100px

  • 问候语出现5秒钟后消失
  • 主要内容等待问候语淡出并显示出来
  • 我用setTimeout实现了这个效果,但我现在想知道如何正确设置clearTimeout

    这是我的密码

    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? 
    }
    
    • 这是我的尝试,代码笔

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

    constructor(){
         this.timer = null;
          //............rest
      }
    
    showGreeting(){
        this.setState({
          greetingDisplay:true,
        })
        this.timer=setTimeout(this.showContent.bind(this),3000);
        ^^^^^^^^^^^
      } 
    
    调用
    showContent
    时,将更新状态,该状态将触发
    render
    ,然后触发
    componentdiddupdate
    生命周期

    组件diddupdate
    中,使用
    this.timer
    清除超时

    componentDidUpdate{
       clearTimeout(this.timer);
    }
    

    您可以轻松使用ES6 arrow功能,而不会产生以下副作用:

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