Javascript React-无法读取未定义的属性,尽管我正在构造函数中绑定函数
我有一个具有以下功能的React容器:Javascript React-无法读取未定义的属性,尽管我正在构造函数中绑定函数,javascript,reactjs,react-native,electron,react-redux,Javascript,Reactjs,React Native,Electron,React Redux,我有一个具有以下功能的React容器: testy() { console.log("HELLO THERE"); } 我的构造函数如下所示: constructor(props) { super(props); this.state = { //... }; this.testy = this.testy.bind(this); } 在我的render()方法中,我执行以
testy() {
console.log("HELLO THERE");
}
我的构造函数如下所示:
constructor(props) {
super(props);
this.state = {
//...
};
this.testy = this.testy.bind(this);
}
在我的render()
方法中,我执行以下操作:
const renderPeople = this.props.people.map(function(person) {
let myPersonFriends = person.friends.map((friend) =>
<span key={friend.id} onClick={(evt) => this.testy()}>
</span>);
return <div key={person.id}> {myPersonFriends}</div>
});
const renderPeople=this.props.people.map(函数(person)){
让myPersonFriends=person.friends.map((friend)=>
this.testy()}>
);
返回{myPersonFriends}
});
所以我这里有不同的人,我遍历每个人,然后遍历他们所有的朋友,然后再做同样的事情,直到我到达终点,遍历所有的人。
所有这些都很好。但是onClick={(evt)=>this.testy()}
不起作用。以前我没有这个dobule嵌套结构,但现在它不再工作了
我很困惑,因为我是在构造函数中绑定函数的,那么它还能是什么呢
错误消息:
未捕获的TypeError:无法读取未定义的属性“testy”
马上
您可以在
映射中释放上下文。应该是
this.props.people.map((person) => {
// use arrow function here ----^
您没有绑定父函数,这就是原因。使用.bind(this)
或使用箭头功能
使用箭头功能
:
const renderPeople = this.props.people.map((person) => {
let myPersonFriends = person.friends.map((friend) =>
<span key={friend.id} onClick={(evt) => this.testy()}/>)
return <div key={person.id}> {myPersonFriends}</div>
});
const renderPeople = this.props.people.map(function(person) {
let myPersonFriends = person.friends.map((friend) =>
<span key={friend.id} onClick={(evt) => this.testy()}/>);
return <div key={person.id}> {myPersonFriends}</div>
}.bind(this));