我有一个具有以下功能的 React 容器:
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>
});
所以我这里有不同的人,我遍历每个人,然后映射他们所有的 friend ,并再次执行相同的操作,直到我到达终点并映射所有的人。
所有这些都运行良好。但是 onClick={(evt) => this.testy()}
不起作用。以前,当我没有这种双嵌套结构时,它曾经可以工作,但现在不再工作了。
我很困惑,因为我在构造函数中绑定(bind)了函数,那么它还能是什么?
错误消息:
Uncaught TypeError: Cannot read property 'testy' of undefined at onClick
最佳答案
您失去了 map
中的上下文。应该是
this.props.people.map((person) => {
// use arrow function here ----^
关于javascript - React - 无法读取未定义的属性,尽管我在构造函数中绑定(bind)了该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43450616/