Javascript 无法读取属性';移除个人';ReactJs中未定义的
我正在尝试使用Javascript 无法读取属性';移除个人';ReactJs中未定义的,javascript,reactjs,Javascript,Reactjs,我正在尝试使用PersonId和url从服务器上的表中删除Person对象。首先,我显示Person对象的列表,在每个对象旁边,我有一个delete按钮来删除对象。我试图将PersonId的值传递给方法removePerson(person)。我使用此方法作为测试,以向控制台显示PersonId,但我得到了以下错误:uncaughttypeerror:无法读取未定义的属性“removePerson”。这是我的代码: return ( <table id="myTab
PersonId
和url
从服务器上的表中删除Person
对象。首先,我显示Person
对象的列表,在每个对象旁边,我有一个delete按钮来删除对象。我试图将PersonId
的值传递给方法removePerson(person)
。我使用此方法作为测试,以向控制台显示PersonId
,但我得到了以下错误:uncaughttypeerror:无法读取未定义的属性“removePerson”
。这是我的代码:
return (
<table id="myTable">
<thead>
<tr>
<th>Person id</th>
<th>Person name</th>
<th>Person Surname</th>
<th>Action </th>
</tr>
</thead>
<tbody>
{this.props.persons.map(function(person , i) {
return(
<tr key={i}>
<td>{person.PersontId}</td>
<td>{person.Name}</Link></td>
<td>{person.Surname}</td>
<td> <button className="btn btn-primary btn-xs" onClick={()=>this.removePerson({person})}
>Delete</button></td>
</tr>
);
})}
</tbody>
</table>
但是,如果我用onClick={()=>console.log({()=>project}}
更改onClick={()=>this.removePerson({person}})
时,每次单击Delete
-按钮,我都会将person
对象发送到控制台。
为什么我会出现此错误以及为什么我无法将person
对象传递给removePerson(person)
?-谢谢 使用es6箭头功能()=>
而不是功能
此
内部回调函数指的是回调方法
{this.props.persons.map((person , i)=> {
return(
<tr key={i}>
<td>{person.PersontId}</td>
<td>{person.Name}</Link></td>
<td>{person.Surname}</td>
<td> <button className="btn btn-primary btn-xs" onClick={()=>this.removePerson({person})}
>Delete</button></td>
</tr>
);
})}
{this.props.persons.map((person,i)=>{
返回(
{person.personId}
{person.Name}
{个人姓氏}
this.removePerson({person}}
>删除
);
})}
您的代码有两个问题
正如@ved指出的,您需要绑定map函数才能使用this.removePerson()
方法
您正在分解person对象并将其作为参数传递给函数。你不需要那样做。将onClick={()=>this.removePerson({person})}
更改为onClick={()=>this.removePerson(person)}
请参见下面的代码
{this.props.persons.map((person , i)=> {
return(
<tr key={i}>
<td>{person.PersontId}</td>
<td>{person.Name}</Link></td>
<td>{person.Surname}</td>
<td> <button className="btn btn-primary btn-xs" onClick={()=>this.removePerson(person)}
>Delete</button></td>
</tr>
);
})}
{this.props.persons.map((person,i)=>{
返回(
{person.personId}
{person.Name}
{个人姓氏}
这个。删除个人(个人)}
>删除
);
})}
您忘记绑定映射回调函数
,使用箭头函数
:{this.props.persons.map((person,i)=>{
@Ved
我更改为es6箭头函数,但当我单击删除
-按钮时,我在控制台中得到了未定义的
。removePerson
-方法写得不正确吗?@carl你传递一个对象,这个.removePerson({person})
就像写这个.removePerson({person:person})
,我会用“this.removePerson(person)`代替它。谢谢@Ved
。我现在看到我的失败了。@Shubham Khatri
谢谢你的解释。很高兴能帮上忙
{this.props.persons.map((person , i)=> {
return(
<tr key={i}>
<td>{person.PersontId}</td>
<td>{person.Name}</Link></td>
<td>{person.Surname}</td>
<td> <button className="btn btn-primary btn-xs" onClick={()=>this.removePerson(person)}
>Delete</button></td>
</tr>
);
})}