有人可以告诉我如何在循环功能中做到这一点吗? 如何将循环函数绑定到构造函数?
class Cookcoo extends React.Component{
constructor(props){
super(props);
this.state={
test:false
}
this.onPlay=this.onPlay.bind(this)
}
onPlay(){
(function loop() {
let randomTime = Math.round(Math.random() * 3000) + 500;
setTimeout(()=> {
this.setState({test:true});
setTimeout(()=>this.setState({test:false}),500)
loop();
}, randomTime);
}());
}
一个简单的解决方案是使用一个额外的变量来存储this
(类上下文(的引用,并在循环函数中使用该变量。
喜欢这个:
onPlay(){
let that = this;
(function loop() {
let randomTime = Math.round(Math.random() * 3000) + 500;
setTimeout(()=> {
that.setState({test:true});
setTimeout(()=>that.setState({test:false}),500)
loop();
}, randomTime);
}());
}
你可以bind
自执行函数,然后用类似.call()
调用内部函数
onPlay() {
(function loop() {
let randomTime = Math.round(Math.random() * 3000) + 500;
setTimeout(() => {
console.log(this);
this.setState({ test: true });
setTimeout(() => this.setState({ test: false }, console.log(this.state.test)), 500)
loop.call(this);
}, randomTime);
}.bind(this)());
}