2016-05-17 57 views
0

在我的React-native應用程序中我試圖在我的listenForItems函數中調用另一個函數,但不斷收到錯誤this.populateArray is not a function. In 'this.populateArray(solutions)', this.populateArray is undefined.我在其他類中執行此操作,並且它正在工作,但出於某種原因,它在此處不起作用。有什麼我失蹤?在另一個函數內反應本地故障調用函數?

populateArray: function(solutions) { 
    var completed = []; 
    var inProgress; 

    for (var i = 0; i < solutions.length; i++) { 
     if (solutions[i].completed == 0) { 
      inProgress = solutions[i].id; 
     } 
     else { 
      completed.push(solutions[i].id); 
     } 
    } 
}, 

listenForItems: function(cluesRef) { 

    var solutions = []; 
    userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){ 
     var solution = snap.val(); 
     for (var i = 0; i < solution.length; i++) { 
      if (solution[0].hunt_id == 0) { 
       solutions.push(solution[0]); 
      } 
     } 
     this.populateArray(solutions); 
    }); 
}, 

回答

3

JavaScript的經典範圍問題。谷歌將幫助加深理解。簡而言之,函數內的「this」一詞指的是該函數。在這個例子中,它引用了您在userSolutionsRef.orderByChild中使用的匿名函數(回調函數)。有很多方法可以解決這個問題。您可以使用ES6(ES2015)箭頭的功能在這種情況下,它變得像

userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', (snap) => { 
    var solution = snap.val(); 
    for (var i = 0; i < solution.length; i++) { 
     if (solution[0].hunt_id == 0) { 
      solutions.push(solution[0]); 
     } 
    } 
    this.populateArray(solutions); 
}); 

或ES5解決方案

var that = this; 
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){ 
     var solution = snap.val(); 
     for (var i = 0; i < solution.length; i++) { 
      if (solution[0].hunt_id == 0) { 
       solutions.push(solution[0]); 
      } 
     } 
     that.populateArray(solutions); 
    });