如何在回调函数中使用setState:ReactJS

9
以下是我用来设置状态的代码。
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.setState,因为它始终未定义。 我尝试过:
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 = thisa.setState,但还是没有成功。

我该如何解决这个问题?


使用 ()=> {} 代替 function(){}。 - Ved
2个回答

20

你需要将回调方法与正确的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)回调方法与之配合使用,例如:

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变量,因为不必要地使用一个多余的变量不是一个好的例子。 - ddeadlink
@ddeadlink,我也曾经更喜欢第一种和第二种方法,在第三种方法中,我建议他如何像在他的问题中使用的那样将引用保存在第三个变量中。 - Mayank Shukla
完全理解您所说的,所以我给了一个赞。 - ddeadlink

1

谢谢您的建议 :) - tonywei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接