如何在回调内执行setState

如何在回调内执行setState

本文介绍了如何在回调内执行setState:ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Following is the code that I used to set the state.

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

虽然数据库创建成功但我无法调用 this.state ,因为它总是未定义。

Rven though the database is created successfully, I cannot call this.state, as it's always undefined.

我试过:

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

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

But it still fails, tried with a = this, and use a.setState, still no luck.

我该如何解决这个问题?

How can I solve this?

推荐答案

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

You need to bind correct this (class context) with callback method, then only you will be able to access the class properties and methods.

可能的解决方案:

1 - 使用,如下所示:

1- Use arrow function, like this:

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

2 - 或者使用 .bind(这个)使用回调方法,如下所示:

2- Or use .bind(this) with callback method, like this:

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

您使用的方式也可以,保存的引用 handleAddNewQuiz 方法中,就像这样:

The way you are using will also work, save the reference of this inside the handleAddNewQuiz method, like this way:

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

这篇关于如何在回调内执行setState:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:28