如何在回调内执行setState:ReactJS

ton*_*wei 7 javascript reactjs

以下是我用来设置状态的代码.

handleAddNewQuiz(event){
    this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
        if(!err){
            this.setState( { quiz : value});  // ERROR: Cannot read property 'setState' of undefined
        }
    });
    event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)

Rven虽然成功创建了数据库,但我无法调用this.state,因为它始终未定义.

我试过了:

self = this;

handleAddNewQuiz(event){
    this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
        if(!err){
            self.setState( { quiz : value});  // ERROR: self.setState is not a function
        }
    });
    event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)

但它仍然失败,尝试a = this和使用a.setState,仍然没有运气.

我怎么解决这个问题?

May*_*kla 13

您需要this使用回调方法绑定正确的(类上下文),然后只有您将能够访问类属性和方法.


可能的解决方案:

1-使用箭头功能,如下所示:

 handleAddNewQuiz(event){
        this.quiz = new Quiz(this.db, this.newQuizName, (err, affected, value) => {
            if(!err){
                this.setState( { quiz : value}); 
            }
        });
        event.preventDefault();
    };
Run Code Online (Sandbox Code Playgroud)

2 -或者使用.bind(this)callback method,类似这样的:

handleAddNewQuiz(event){
    this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
        if(!err){
            this.setState( { quiz : value});  
        }
    }.bind(this));
    event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)

您使用的方式也可以,保存方法this内部的引用handleAddNewQuiz,如下所示:

handleAddNewQuiz(event){
    let self = this;    //here save the reference of this
    this.quiz = new Quiz(this.db, this.newQuizName, function(err, affected, value){
        if(!err){
            self.setState( { quiz : value});  
        }
    });
    event.preventDefault();
};
Run Code Online (Sandbox Code Playgroud)