我是React新手和挣扎 . 以下代码段会出现以下错误
“未捕获的TypeError:无法读取未定义的属性'creationDate'” .
如果我从render中的populateTableRows和creationDate函数移动代码,一切都很好 . SurveyList从另一个组件获取它的数据 . 我知道这是非常丑陋的组件,所有其他建议也是受欢迎的,但我最感兴趣的是这个特定的错误 .
import React from 'react';
import ReactDOM from 'react-dom';
import { Table, Tr, Td } from 'reactable';
class SurveyList extends React.Component{
constructor(props) {
super(props);
this.state = {
isSaved: false,
surveys: []
};
this.creationDate = this.creationDate.bind(this);
this.populateTableRows = this.populateTableRows.bind(this);
}
creationDate (obj){
return new Date(obj._id.time).toISOString().slice(0,10);
}
populateTableRows(surveys){
var surveyRows = [];
surveys.forEach(function(obj){
surveyRows.push(
<Tr key={obj.surveyId}>
<Td column="SurveyId">{obj.surveyId}</Td>
<Td column="Survey name">{obj.surveyName}</Td>
<Td column="Creation date">{this.creationDate(obj)}</Td>
<Td column=""><ModalDialog key={obj.surveyId}
survey={obj}
/></Td>
</Tr>
);
});
return surveyRows;
}
render() {
var surveys = Array.from(this.props.surveys);
var surveyRows = this.populateTableRows(surveys);
return (
<Table className="table" id="table" sortable={true} filterable={['SurveyId', 'Survey name', 'Creation date']}>
{surveyRows}
</Table>
)
}
}
1 回答
@ctrlplusb的评论是正确的 . 当您在
surveys.forEach
调用中使用function
关键字时,其内容将获得一个新范围 - 因此是一个新的this
,由于它不属于任何对象,因此未定义 . 有几种解决方案 .最漂亮的是使用ES2015中通过Babel提供的新胖箭头(“lexical
this
”)语法 . 它创建了一个维护定义范围的函数 . 例如 . :但是,最简单的方法是使用second argument that forEach takes,这是
this
使用: