如何在回调中执行 setState:ReactJS

IT技术 javascript reactjs
2021-01-16 03:00:35

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

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,因为它始终未定义。

我试过:

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,仍然没有运气。

我该如何解决这个问题?

2个回答

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


可能的解决方案:

1-使用箭头功能,像这样:

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

2-或使用.bind(this)with 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();
};

您使用的方式也适用,保存方法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();
};
我宁愿选择 1 和 2 变体因为不必要地使用另一个变量并不是很好的例子
2021-03-16 03:00:35
@ddeadlink,我也曾经更喜欢第一种和第二种方式,在第三种方式中,我建议他如何在第三个变量中保存引用,就像他在他的问题中使用的那样。
2021-03-29 03:00:35
完全明白你的目的,所以我投了赞成票)
2021-04-07 03:00:35

Mayank 的回答是正确的。或者你可以使用 https://www.npmjs.com/package/core-decorators

并在函数前使用@autobind 装饰器。

谢谢你的建议:)
2021-03-28 03:00:35