简体   繁体   中英

How to do setState inside callback: 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();
};

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

I tried:

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

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.


Possible Solutions:

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

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

Mayank's answer is correct.. Alternatively you can use https://www.npmjs.com/package/core-decorators

and use the @autobind decorator before the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM