React - 无法读取未定义的 属性,尽管我在构造函数中绑定了函数

React - Cannot read property of undefined, although I am binding the function in the constructor

我有一个具有以下功能的 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>
});

所以我这里有不同的人,我遍历每个人,然后映射他们所有的朋友,然后再做同样的事情,直到我到达终点并映射完所有人。 所有这一切都很好。但是 onClick={(evt) => this.testy()} 不起作用。以前没有这种双嵌套结构的时候还可以,现在不行了

我很困惑,因为我在构造函数中绑定了函数,那还能是什么?

错误信息:

Uncaught TypeError: Cannot read property 'testy' of undefined at onClick

您在 map 中丢失了上下文。应该是

this.props.people.map((person) => {
// use arrow function here ----^

你不是binding parent function,这就是原因。使用 .bind(this) 或使用 arrow function.

通过使用 arrow function:

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>
});

通过使用 .bind(this):

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));