2017-05-25 18 views
0

我在函數內有以下功能,我試圖檢查一個對象的狀態。問題是,當我運行代碼時,它告訴我,this.state不是一個對象。this.state不是一個對象時,在一個循環內

convertNeighbourArrayIntoMap(neighbourData) { 

     var neighbourCategoryMap = {}; // Create the blank map 

     neighbourData.forEach(function(neighbourItem) { 

      if(this.state.searchString == ""){ 
       console.log("No Search String"); 
      } 

      if (!neighbourCategoryMap[neighbourItem.category]) { 
       // Create an entry in the map for the category if it hasn't yet been created 
       neighbourCategoryMap[neighbourItem.category] = []; 
      } 

      neighbourCategoryMap[neighbourItem.category].push(neighbourItem); 

     }); 

     return neighbourCategoryMap; 
    } 

這工作,但我需要它在循環內。

convertNeighbourArrayIntoMap(neighbourData) { 

     var neighbourCategoryMap = {}; // Create the blank map 

if(this.state.searchString == ""){ 
       console.log("No Search String"); 
      } 

     neighbourData.forEach(function(neighbourItem) { 

      if (!neighbourCategoryMap[neighbourItem.category]) { 
       // Create an entry in the map for the category if it hasn't yet been created 
       neighbourCategoryMap[neighbourItem.category] = []; 
      } 

      neighbourCategoryMap[neighbourItem.category].push(neighbourItem); 

     }); 

     return neighbourCategoryMap; 
    } 

回答

2

這是因爲forEach的回調不拾取相同的上下文。最簡單的解決它切換到箭頭的功能(如果可能):

 neighbourData.forEach((neighbourItem) => { 

      if(this.state.searchString == ""){ 
       console.log("No Search String"); 
      } 

      if (!neighbourCategoryMap[neighbourItem.category]) { 
       // Create an entry in the map for the category if it hasn't yet been created 
       neighbourCategoryMap[neighbourItem.category] = []; 
      } 

      neighbourCategoryMap[neighbourItem.category].push(neighbourItem); 

     }); 

如果沒有可用箭頭的功能,然後bindforEach功能:

 neighbourData.forEach(function(neighbourItem) { 

      if(this.state.searchString == ""){ 
       console.log("No Search String"); 
      } 

      if (!neighbourCategoryMap[neighbourItem.category]) { 
       // Create an entry in the map for the category if it hasn't yet been created 
       neighbourCategoryMap[neighbourItem.category] = []; 
      } 

      neighbourCategoryMap[neighbourItem.category].push(neighbourItem); 

     }.bind(this)); 
1

使用箭頭函數,以便保持this上下文預期:

neighbourData.forEach((neighbourItem) => { 
... 
    if (!this.state.searchString.length) { 
    console.log("No Search String"); 
    } 
... 
相關問題