我在组件内的功能中访问this.state
时遇到问题。我已经在SO上找到了this问题,并将建议的代码添加到我的构造函数中:
class Game extends React.Component {
constructor(props){
super(props);
...
this.state = {uid: '', currentTable : '', currentRound : 10, deck : sortedDeck};
this.dealNewHand = this.dealNewHand.bind(this);
this.getCardsForRound = this.getCardsForRound.bind(this);
this.shuffle = this.shuffle.bind(this);
}
// error thrown in this function
dealNewHand(){
var allCardsForThisRound = this.getCardsForRound(this.state.currentRound);
}
getCardsForRound(cardsPerPerson){
var shuffledDeck = this.shuffle(sortedDeck);
var cardsForThisRound = [];
for(var i = 0; i < cardsPerPerson * 4; i++){
cardsForThisRound.push(shuffledDeck[i]);
}
return cardsForThisRound;
}
shuffle(array) {
...
}
...
...
它仍然不起作用。 this.state.currentRound
未定义。有什么问题?
答案 0 :(得分:5)
我想出了一些有用的东西。我将构造函数中绑定this.getCardsForRound = this.getCardsForRound.bind(this, this.state.currentRound);
的代码更改为:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
答案 1 :(得分:0)
以这种方式编写您的函数:
dealNewHand = () => {
var allCardsForThisRound =
this.getCardsForRound(this.state.currentRound);
}
getCardsForRound = (cardsPerPerson) => {
var shuffledDeck = this.shuffle(sortedDeck);
var cardsForThisRound = [];
for(var i = 0; i < cardsPerPerson * 4; i++){
cardsForThisRound.push(shuffledDeck[i]);
}
return cardsForThisRound;
}
http://www.react.express/fat_arrow_functions
关键字的绑定在胖箭头函数的外部和内部是相同的。这与使用function声明的函数不同,函数可以在调用时将其绑定到另一个对象。维护此绑定对于映射等操作非常方便:this.items.map(x =&gt; this.doSomethingWith(x))。