簡體   English   中英

無法使用this.function(React.js)讀取未定義的屬性“ function”

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

我已經研究這個主題一段時間了,完全陷入困境。 我正在使用React.js ,並使用es6類組件。

當我在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 [];
  }

正如周華健的H上述意見提到的,問題是, this一次,你進入未綁定map功能。 您可以將thisArg傳遞給map函數,或者將該函數移至綁定到構造函數中的單獨的類函數。 看起來像這樣(未經測試):

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
}

首先在this.state聲明中的inputValue inputValue: '',之后刪除逗號。 同樣在filterCourses函數中, if(this.showDate)條件正在尋找showDate屬性而不是函數。 您的showDate函數也需要一個日期。

您還需要一個render函數,因為任何react組件都需要一個render函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM