Javascript ReactJS:setTimeout() 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36270422/
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
ReactJS: setTimeout() not working?
提问by jbarradas
Having this code in mind:
记住这个代码:
var Component = React.createClass({
getInitialState: function () {
return {position: 0};
},
componentDidMount: function () {
setTimeout(this.setState({position: 1}), 3000);
},
render: function () {
return (
<div className="component">
{this.state.position}
</div>
);
}
});
ReactDOM.render(
<Component />,
document.getElementById('main')
);
Isn't the state supposed to change only after 3 seconds? It's changing immediately.
状态不是应该在 3 秒后才改变吗?它立即发生变化。
My main goal here is to change the state every 3 seconds (with setInterval()
), but since it was not working, I tried setTimeout()
, which is not working either. Any lights on this? Thanks!
我在这里的主要目标是每 3 秒更改一次状态(使用setInterval()
),但由于它不起作用,我尝试了setTimeout()
,这也不起作用。有这方面的灯吗?谢谢!
回答by Daniel A. White
Do
做
setTimeout(
function() {
this.setState({position: 1});
}
.bind(this),
3000
);
Otherwise, you are passing the result of setState
to setTimeout
.
否则,您将传递setState
to的结果setTimeout
。
回答by Steven Scaffidi
setTimeout(() => {
this.setState({ position: 1 });
}, 3000);
The above would also work because the ES6 arrow function does not change the context of this
.
由于 ES6 箭头函数不会改变this
.
回答by Khalid Azam
Anytime we create a timeout we should s clear it on componentWillUnmount, if it hasn't fired yet.
任何时候我们创建超时我们都应该在 componentWillUnmount 上清除它,如果它还没有被触发。
let myVar;
const Component = React.createClass({
getInitialState: function () {
return {position: 0};
},
componentDidMount: function () {
myVar = setTimeout(()=> this.setState({position: 1}), 3000)
},
componentWillUnmount: () => {
clearTimeout(myVar);
};
render: function () {
return (
<div className="component">
{this.state.position}
</div>
);
}
});
ReactDOM.render(
<Component />,
document.getElementById('main')
);
回答by Fernando Lopes
I know this is a little old, but is important to notice that React recomends to clear the interval when the component unmounts: https://reactjs.org/docs/state-and-lifecycle.html
我知道这有点旧,但重要的是要注意 React 建议在组件卸载时清除间隔:https://reactjs.org/docs/state-and-lifecycle.html
So I like to add this answer to this discussion:
所以我想在这个讨论中添加这个答案:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
回答by tymeJV
setState
is being invoked immediately due to the parenthesis! Wrap it in an anonymous function, then call it:
setState
由于括号,正在立即调用!将它包装在一个匿名函数中,然后调用它:
setTimeout(function() {
this.setState({position: 1})
}.bind(this), 3000);
回答by Advis
You didn't tell who called setTimeout
你没有告诉谁叫 setTimeout
Here how you call timeout without calling additional functions.
在这里,您如何在不调用其他函数的情况下调用超时。
1. You can do this without making additional functions.
1.您可以在不制作附加功能的情况下执行此操作。
setTimeout(this.setState.bind(this, {position:1}), 3000);
Uses function.prototype.bind()
使用function.prototype.bind()
setTimeout takes the location of the function and keeps it in the context.
setTimeout 获取函数的位置并将其保存在上下文中。
2. Another way to do the same even by writing even less code.
2. 即使编写更少的代码也能做到这一点的另一种方法。
setTimeout(this.setState, 3000, {position:1});
Probablyuses the same bind method at some point
可能在某个时候使用相同的绑定方法
The setTimeout only takes the location of the function and the function already has the context? Anyway, it works!
setTimeout 只取函数的位置,函数已经有了上下文?无论如何,它有效!
NOTE: These work with any function you use in js.
注意:这些适用于您在 js 中使用的任何函数。
回答by Xin
Your code scope (this
)will be your window
object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000)
will crash this way.
您的代码范围 ( this
)将是您的window
对象,而不是您的反应组件,这就是为什么setTimeout(this.setState({position: 1}), 3000)
会以这种方式崩溃。
That comes from javascript not React, it is js closure
那来自javascript而不是React,它是js闭包
So, in order to bind your current react component scope, do this:
因此,为了绑定您当前的 react 组件范围,请执行以下操作:
setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);
Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:
或者,如果您的浏览器支持 es6 或者您的 projs 支持将 es6 编译为 es5,也可以尝试使用箭头函数,因为箭头函数是为了解决“这个”问题:
setTimeout(()=>this.setState({position: 1}), 3000);
回答by Darryl Fabian
There's a 3 ways to access the scope inside of the 'setTimeout' function
有 3 种方法可以访问“setTimeout”函数内的范围
First,
第一的,
const self = this
setTimeout(function() {
self.setState({position:1})
}, 3000)
Second is to use ES6 arrow function, cause arrow function didn't have itself scope(this)
其次是使用ES6箭头函数,导致箭头函数本身没有作用域(this)
setTimeout(()=> {
this.setState({position:1})
}, 3000)
Third one is to bind the scope inside of the function
第三个是在函数内部绑定作用域
setTimeout(function(){
this.setState({position:1})
}.bind(this), 3000)
回答by KARTHIKEYAN.A
You did syntax declaration error, use proper setTimeout declaration
你做了语法声明错误,使用正确的 setTimeout 声明
message:() => {
setTimeout(() => {this.setState({opened:false})},3000);
return 'Thanks for your time, have a nice day !
}