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
setTimeout and clearTimeout in reactJS
提问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 像素
- Greeting appears for 5seconds and fades out
- Main content waits until greeting fades out and gets displayed.
- 问候语出现 5 秒然后淡出
- 主要内容等待问候语淡出并显示。
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 );
}

