【问题标题】:How to do setState inside callback: ReactJS如何在回调中执行 setState:ReactJS
【发布时间】:2023-03-15 04:20:01
【问题描述】:

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

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,还是不行。

我该如何解决这个问题?

【问题讨论】:

  • 使用 ()=> {} 而不是使用 function(){}。

标签: javascript reactjs


【解决方案1】:

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


可能的解决方案:

1- 使用arrow function,像这样:

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

2-或者使用.bind(this)和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 变体因为不必要地使用另一个变量不是很好的例子
  • @ddeadlink,我以前也喜欢第一种和第二种方式,在第三种方式中,我建议他如何将引用保存在第三个变量中,就像他在他的问题中使用的那样。
  • 完全理解你的意思,所以我赞成)
【解决方案2】:

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

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

【讨论】:

  • 感谢您的建议 :)
猜你喜欢
  • 2010-11-04
  • 2016-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2013-09-26
  • 1970-01-01
相关资源
最近更新 更多