![](/img/trans.png)
[英]function returning the data to filter and map that show error React.js TypeError: Cannot read property 'val' of undefined
[英]Cannot read property 'function' of undefined using this.function (React.js)
我已经研究这个主题一段时间了,完全陷入困境。 我正在使用React.js
,并使用es6类组件。
当我在filterCourses
函数内部调用this.showDate
,它声称无法读取undefined
的showDate
属性。 这意味着关键字this
是undefined
。
我曾尝试结合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.