2017-04-07 34 views
1

以下是我用來設置狀態的代碼。如何做setState裏面的回調:ReactJS

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儘管數據庫創建成功,我不能叫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,仍然沒有運氣。

我該如何解決這個問題?

+0

use()=> {}改爲使用function(){}。 – Ved

回答

4

您需要使用回調方法將正確的this(類上下文)綁定,那麼只有您將能夠訪問類屬性和方法。


可能的解決方案:

使用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(); 
}; 
+0

我寧願選擇1和2變體因爲不必要的使用多一個變量是不是很好的例子 – ddeadlink

+0

@ddeadlink,我也習慣於第一和第二種方式,在第三種方式,我建議他如何保存參考像他在他的問題中使用的第三個變量。 –

+0

tottaly瞭解你是什麼導致,所以我upvoted) – ddeadlink