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

标签 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() 方法中,我这样做:

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/

相关文章:

javascript - 如何使用箭头键浏览 <li> 元素 - jQuery?

javascript - 从客户端 (AngularJS) 向 Node.js 服务器发送图像

html5media提取的代码不起作用

javascript - 为什么 React 类中的 'this' 与 Js 事件处理程序中的不同?

javascript - React Router - 从未直接渲染

reactjs - 如何提供 `babel-preset-react-app` 环境变量?

android - React-Native(Android)-任务 ':app:transformClassesWithMultidexlistForRelease'的执行失败

javascript - 使用 PhoneGap 自定义 iPhone 相机 UI

javascript - 闪屏 react 原生

javascript - Xcode 10 更新后 React Native 无法正常工作