错误:this.friendChat不是函数(Jquery+;react)
我有一个jsx文件,它在页面加载时创建错误:this.friendChat不是函数(Jquery+;react),jquery,reactjs,state,jsx,Jquery,Reactjs,State,Jsx,我有一个jsx文件,它在页面加载时创建元素。这些项是基于ajax返回值创建的 对于每个元素,我以编程方式添加“click”事件,该事件调用一个react函数(friendChat)。但是在实现这一点时,我得到了以下错误。(但我可以获得其他属性,这些属性是在构造函数中初始化的。) 错误:this.friendChat不是一个函数 下面是我的jsx文件 提前谢谢 jsx文件 import React from 'react' class Home extends React.Component
元素。这些
项是基于ajax返回值创建的
对于每个
元素,我以编程方式添加“click”事件,该事件调用一个react函数(friendChat)。但是在实现这一点时,我得到了以下错误。(但我可以获得其他属性,这些属性是在构造函数中初始化的。)
- 错误:this.friendChat不是一个函数
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
从“React”导入React
类Home扩展了React.Component{
建造师(道具){
超级(道具);
this.state={username:“Anu”};
this.friendChat=this.friendChat.bind(this);
}
friendChat(friendId)
{
日志(“点击好友id:+friendId”);
}
componentDidMount(){
log('Component dod MOUNT!');
$(文档).ready(函数(){
$.ajax({
键入:“获取”,
url:“/friends/myFriends”,
成功:功能(数据){
如果(数据==“没有朋友”)
{
console.log(“没有朋友存在”);
document.getElementById('friends').innerHTML=“请添加
“朋友”;
}
其他的
{
console.log(“朋友:+数据”);
//在div中显示好友
对于(变量i=0;i
)
}
}
导出默认主页
解决方案1:将该方法中的所有函数转换为fat arrow,一切都将正常工作
例如:
$(document).ready(function(){...})
componentDidMount() {
const self = this;
....
self.friendChat(self.id);
}
改为:
$(document).ready(()=>{...})
解决方案2:将此关键字的引用存储到变量中,然后访问该变量
例如:
$(document).ready(function(){...})
componentDidMount() {
const self = this;
....
self.friendChat(self.id);
}
在ajax jquery请求中使用纯javascript的原因可能重复如果您使用jquery,请遵循使用jquery,但不要在同一函数中使用jquery和javascript,这会导致错误,就像yoursIt解释得很好一样。谢谢@Andrew Li。我从@Giovanni那里得到了确切的答案Lobitos@abhilash如果副本有帮助,请接受副本单击问题上方的黄色横幅。