无法使用 this.function (React.js) 读取未定义的 属性 'function'

Cannot read property 'function' of undefined using this.function (React.js)

我研究这个话题有一段时间了,完全卡住了。我正在使用 React.js,并使用 es6 class 组件。

当我在 filterCourses 函数中调用 this.showDate 时,它声称无法读取 undefinedshowDate 属性。这意味着关键字 thisundefined.

我试过在构造函数中绑定 this

问题

如何定义 this


class Upcoming_Training extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
    }
  }
  componentDidMount() {}
  showDate(date) {
    // Creates a more readable date
    if (date) {
      date = date.substring(0, date.indexOf("T"));
      let dateArr = date.split('-');
      return dateArr[1] + '/' + dateArr[2] + '/' + dateArr[0];
    }
  }
  filterCourses() {
    let courseRows = [];
    if (this.props.upcoming_training != []) {
      if (this.showDate) {
        let courseRows = this.props.upcoming_training.map(function (
          course, index) {
          return <tr>
                   <th><button className='btn btn-sm btn-primary'> More Info </button></th> {/*Will make this button do something later*/}
                   <td>{course.Course}</td>
                   <td> {(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td>
                   <td>{this.showDate(course.Start)}</td>
                   <td>{this.showDate(course.End)}</td>
                   <td>{(course.IsOnline ? "Online" : "On-Site")}</td>
                 </tr>
        })
      }
      return courseRows;
    }
    return [];
  }

先去掉this.state声明中inputValue: '',后面的逗号。同样在您的 filterCourses 函数中, if(this.showDate) 条件正在寻找 showDate 属性 而不是函数。您的函数 showDate 也需要一个日期。

您还需要一个渲染函数,因为任何 React 组件都需要有一个渲染函数。

正如 Emil H 在上面的评论中提到的,问题是一旦您输入 map 函数,this 就没有绑定。您可以将 thisArg 传递给 map 函数,或者将该函数移动到您在构造函数中绑定的单独 class 函数。看起来像这样(未经测试):

class Upcoming_Training extends Component {
  constructor(props) {
    super(props);
    this.filterCourses = this.filterCourses.bind(this);
    this.renderCourseRow = this.renderCourseRow.bind(this);
  }

  showDate(date) {
    // Format date...
  }

  renderCourseRow(course, index) {
    return (
      <tr key={index}>
        <th><button className='btn btn-sm btn-primary'> More Info </button></th>
        <td>{course.Course}</td>
        <td>{(course.Name.includes("OL -") ? course.Name.slice(5) : course.Name)}</td>
        <td>{this.showDate(course.Start)}</td>
        <td>{this.showDate(course.End)}</td>
        <td>{(course.IsOnline ? "Online" : "On-Site")}</td>
      </tr>
    )
  }

  filterCourses() {
    if (this.props.upcoming_training != []) {
      return this.props.upcoming_training.map(renderCourseRow);
    }
    return [];
  }

  // ...Rest of component
}