“ this”在 map 函数 Reactjs 中是未定义的

我正在和 Reactjs 合作,编写一个菜单组件。

"use strict";


var React = require("react");
var Menus = React.createClass({


item_url: function (item,categories,articles) {
console.log('afdasfasfasdfasdf');
var url='XXX';
if (item.type == 1) {
url = item.categoryId == null ? 'javascript:void(0)' : path('buex_portal_browse_category', {slug: categories[item.categoryId].slug});
} else if (item.type == 2) {
url = item.articleId == null ? 'javascript:void(0)' : path('buex_portal_view_article', {slug: articles[item.articleId].slug, id: item.articleId});
} else {
url = item.url;
}
return url;
},


render: function () {
//   console.log(this.props.menus);  // return correctly
var menuElements = this.props.menus.map(function (item1) { // return fault : 'cannot read property 'props' of undefined '
return (
<div>
<li>
<a href={this.item_url(item1, this.props.categories, this.props.articles )}>{item1.name} // the same fault above
<i class="glyphicon glyphicon-chevron-right pull-right"></i>
</a>
<div class="sub-menu">
<div>
{item1._children.map(function (item2) {
return (
<div>
<h4>
<a href={this.item_url(item2, this.props.categories, this.props.articles)}>{ item2.name }</a>
</h4>
<ul>
{item2._children.map(function (item3) {
return (
<div><li><a href={this.item_url(item3, this.props.categories, this.props.articles) }>{ item3.name }</a></li></div>
);
})}
</ul>
</div>
);
})}
</div>
</div>
</li>
</div>
);
});


return (
<div class="menu">
<ul class="nav nav-tabs nav-stacked">
{menuElements}
</ul>
</div>
);
}
});

每当我在 map 函数中使用“ this”时,它都是未定义的,但是在外部它是没有问题的。

错误是:

“无法读取未定义的属性‘道具’”

谁来帮帮我

53519 次浏览

Array.prototype.map() takes a second argument to set what this refers to in the mapping function, so pass this as the second argument to preserve the current context:

someList.map(function(item) {
...
}, this)

Alternatively, you can use an ES6 arrow function to automatically preserve the current this context:

someList.map((item) => {
...
})