2017-08-29 83 views
-1

我有一個jsx文件,它在頁面加載時創建<li>元素。這些<li>項目是基於ajax返回值創建的。錯誤:this.friendChat不是函數(jquery + react)

對於每一個<li>元素,我將通過編程方式添加「click」事件,它會調用反應函數(friendChat)。但是,在實現這一點時,我收到以下錯誤。 (但我能得到其他特性,這裏面初始化構造。)

  • 錯誤:this.friendChat不是一個函數

以下是我的JSX文件。

在此先感謝。

JSX文件

import React from 'react' 

class Home extends React.Component { 


constructor(props) { 

    super(props); 
    this.state = {username: "Anu"}; 
    this.friendChat = this.friendChat.bind(this); 


    } 


    friendChat(friendId) 
    { 
     console.log("Clicked friend id: "+ friendId); 

    } 





componentDidMount() { 
    console.log('Component DID MOUNT!'); 


$(document).ready(function(){ 


    $.ajax({ 
     type: "GET", 
     url: "/friends/myFriends", 
     success: function(data){ 

      if (data == "No friends") 
      { 
       console.log("No friends exist"); 
       document.getElementById('friends').innerHTML = "Please add 
    friends"; 
      } 
      else 
      { 
      console.log("Friends: "+data); 
      //Displaying friends in div 
      for (var i = 0; i < data.length; i++) 
       { 
        console.log("Friend: "+ data[i]); 
       var li=document.createElement("li"); 
       //var br=document.createElement("br"); 
       li.appendChild(document.createTextNode(data[i])); 
       li.setAttribute("id",data[i]); 


       console.log(this.state.username); 
      //It's Printing correctusername (Anu) initialised inside 
      //the constructor 


       //Adding on click event for each friend 

       li.addEventListener("click", function() { 
       this.friendChat(this.id); }, false); 
       //Here it's showing the error of this.friendChat is not a 
       //function 

      //Appending list item to document 
      document.getElementById("friends").appendChild(li); 
      } 
     } 


    }.bind(this) 
}); 


} 



render() { 
    return (


    <div> 



     <div className="home_recentfriends"> 
      <ul id="friends"></ul> 
     </div> 


    </div> 


    ) 
    } 


} 

export default Home 
+0

的可能的複製[?如何訪問正確的\'這\'回調內(https://stackoverflow.com/questions/20279484/how-to-access-正確的這裏面回調) – Li357

+0

爲什麼你在jQuery jQuery請求中使用javascript pure如果你使用jquery,請遵循使用jquery,但不要在同一個函數中使用jquery和javascript,這會導致類似你的錯誤 –

+0

It解釋得非常好。感謝@安德魯李。 – abhilash

回答

1

解決方案1:變換方法內的所有功能轉化爲脂肪箭頭,一切都將正常工作。

實施例:

$(document).ready(function(){...}) 

變成:

$(document).ready(()=>{...}) 

解決方案2:商店這個關鍵字的參考成一個變量,並訪問該變量代替。

例子:

componentDidMount() { 
const self = this; 

.... 

self.friendChat(self.id); 

} 
+0

非常感謝你......它完美的工作。 – abhilash