微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何在回调内执行setState: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();
};

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

我试过了:

self = this;

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

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

我怎么解决这个问题?

解决方法

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

可能的解决方案:

1-使用arrow function,如下所示:

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

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

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

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

handleAddNewQuiz(event){
    let self = this;    //here save the reference of this
    this.quiz = new Quiz(this.db,value){
        if(!err){
            self.setState( { quiz : value});  
        }
    });
    event.preventDefault();
};

原文地址:https://www.jb51.cc/js/150066.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐