【问题标题】:React - Cannot read property of undefined, although I am binding the function in the constructorReact - 无法读取未定义的属性,尽管我在构造函数中绑定了函数
【发布时间】:2017-09-13 00:29:09
【问题描述】:

我有一个具有以下功能的 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) =&gt; this.testy()} 不起作用。它以前可以工作,当时我没有这种双嵌套结构,但现在它不再工作了。

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

错误信息:

未捕获的类型错误:无法读取未定义的属性“testy” 在点击时

【问题讨论】:

    标签: javascript reactjs react-native electron react-redux


    【解决方案1】:

    你在map 中失去了上下文。应该是

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

    【讨论】:

      【解决方案2】:

      你不是 binding 父 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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多