【问题标题】:Error: this.friendChat is not a function (Jquery + react )错误:this.friendChat 不是函数(Jquery + react)
【发布时间】:2018-02-06 08:02:39
【问题描述】:

我有一个 jsx 文件,它在页面加载时创建 <li> 元素。这些<li> 项是根据ajax 返回值创建的。

对于每个<li> 元素,我以编程方式添加“点击”事件,该事件调用反应函数 (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

【问题讨论】:

  • 如果你使用 jquery,为什么你在 ajax jquery 请求中使用 javascript pure,请遵循使用 jquery 但不要在同一个函数中使用 jquery 和 javascript,这会导致像你这样的错误
  • 解释得很好。谢谢@Andrew Li。
  • 我从@Giovanni Lobitos 得到了准确的答案
  • @abhilash 如果副本有帮助,请点击问题上方的黄色横幅接受副本。

标签: jquery reactjs state jsx


【解决方案1】:

解决方案 1: 将该方法中的所有函数转换为胖箭头,一切都会正常工作。

例子:

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

改成:

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

解决方案 2: 将 this 关键字的引用存储到变量中,然后访问该变量。

例子:

componentDidMount() {
 const self = this;

 ....

 self.friendChat(self.id);

}

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 2019-04-21
    • 2017-08-16
    • 2019-09-21
    • 2014-08-02
    • 2014-03-04
    • 1970-01-01
    相关资源
    最近更新 更多