亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在地圖函數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 關注
  • 655 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號