【问题标题】:React: Cannot read property 'method()' of undefined when method is bound [duplicate]反应:绑定方法时无法读取未定义的属性“方法()”[重复]
【发布时间】:2018-07-24 03:14:17
【问题描述】:

大家好,我正在尝试在 react 中渲染一个表格,该表格在单击时将行设置为选中状态。

单击该行时出现这样的错误:Uncaught TypeError: Cannot read property 'setSelected' of undefined

对此有很多问题,解决方案似乎是将行 this.setSelected = this.setSelected.bind(this); 添加到构造函数中,以便实际可以访问该函数。

我已经知道这样做了,正如您在下面看到的那样,我已经做到了,但它仍然给我错误。我完全被难住了。

import React, { Component } from 'react';

class ShowsList extends Component {
  constructor(props) {
    super(props);
    this.state = {selected: {showID: null, i: null}};
    this.setSelected = this.setSelected.bind(this);
  }

  setSelected(event, showID, i) {
    this.setState({
      selected: {showID, i}
    });
    console.log(this.state.selected);
  }


  render() {
    return (
      <div className="shows-list">

      <table className="table">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Name</th>
      <th scope="col">Location</th>
      <th scope="col">Date</th>
      <th scope="col">Time</th>
    </tr>
  </thead>
  <tbody>
    {this.props.shows.map( function(show, i) {
      return (
        <tr
          key={i}
          onClick={(e) => {this.setSelected(e, show._id, i)}}>
          <td>{i+1}</td>
          <td>{show.eventName}</td>
          <td>{show.location}</td>
          <td>{show.date}</td>
          <td>{show.startTime}</td>
        </tr>);
    })}
  </tbody>
</table>

      </div>
    );
  }
}

export default ShowsList;

【问题讨论】:

    标签: javascript node.js reactjs


    【解决方案1】:

    用function关键字声明的Javascript函数有自己的this上下文,所以this.props.shows.map( function(show, i)里面的this不引用类。您可以对函数声明使用箭头语法,这将轻松解析this 的值。改变

    this.props.shows.map(function(show, i)
    

    this.props.shows.map((show, i ) => {
    

    【讨论】:

    • 哦,哇,对于刚接触 JS 的人来说,这是一个令人讨厌的小问题。非常感谢,我在编写 JSX 时会牢记这一点。
    猜你喜欢
    • 2017-01-30
    • 2019-07-13
    • 1970-01-01
    • 2018-10-06
    • 2019-06-15
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多