如何在回调中执行 setState:ReactJS [英] How to do setState inside callback: ReactJS

查看:34
本文介绍了如何在回调中执行 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?

推荐答案

您需要使用回调方法绑定正确的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(this)回调方法,像这样:

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

你用的方法也行,把this的引用保存在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆