我需要在主要组件时设置Interval。
我试着在构造函数中设置它,比如
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
。