Reactjs 如何将其绑定到React中的递归函数中?

Reactjs 如何将其绑定到React中的递归函数中?,reactjs,function,this,bind,Reactjs,Function,This,Bind,有人能告诉我如何在循环功能中工作吗?如何将循环函数绑定到构造函数 class Cookcoo extends React.Component{ constructor(props){ super(props); this.state={ test:false } this.onPlay=this.onPlay.bind(this) } onPlay(){ (fu

有人能告诉我如何在循环功能中工作吗?如何将循环函数绑定到构造函数

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);

        }());
    }

一个简单的解决方案是使用一个额外的变量来存储此(类上下文)的引用,并在循环函数中使用该变量

像这样:

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);
    }());
}

您可以
绑定
自执行函数,然后使用
.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)());
  }

一个简单的解决方案是
let that=this
并使用
内部循环函数。非常好,非常感谢。您还可以使用胖箭头函数声明循环。