我需要setInterval当主要成分。我试图在构造函数中设置它
constructor(props) {
super(props);
this.props.fetchUserInfo();
this.props.fetchProducts();
setInterval(console.log('1'), 1000);
}
或里面 componentDidMount
componentDidMount = () => {
setInterval(console.log('1'), 1000);
};
但它总是记录一次“ 1”。如何正确启动间隔?
setInterval(console.log('1'), 1000);
调用 console.log('1')
并将其返回值传递到setInterval
,恰好foo(bar())
调用 bar
并将其返回值传递到的方式foo
。
您想传递一个函数引用给它:
setInterval(function() {
console.log('1');
}, 1000);
或者,如果您需要this
在该函数内部保持一致,并且尚未使用ES2015语法,请执行以下操作:
setInterval(function() {
console.log('1');
}.bind(this), 1000);
Function#bind
返回一个新函数,该函数在调用时会使用this
您提供的值调用原始函数。
或者,如果您使用的是ES2015语法
setInterval(() => {
console.log('1');
}, 1000);
它将关闭this
创建它的位置,不需要bind
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句