为了账号安全,请及时绑定邮箱和手机立即绑定

在地图函数Reactjs中,“this”未定义

在地图函数Reactjs中,“this”未定义

慕虎7371278 2019-09-20 16:53:04
我正在使用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>每当我在map函数中使用'this'时它是未定义的,但在它之外没有问题。错误:“无法读取未定义的属性'道具'”有人帮帮我!:((
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

Array.prototype.map()采用第二个参数来设置this映射函数中引用的内容,因此传递this为第二个参数以保留当前上下文:


someList.map(function(item) {

  ...

}, this)

或者,您可以使用ES6 箭头功能自动保留当前this上下文:


someList.map((item) => {

  ...

})


查看完整回答
反对 回复 2019-09-20
  • 1 回答
  • 0 关注
  • 579 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信