【问题标题】:Javascript `this` - reference containing object [duplicate]Javascript`this`-包含对象的引用[重复]
【发布时间】:2015-10-28 14:27:10
【问题描述】:

我正在使用 Javascript 和 React 来构建前端。我不确定如何引用包含对象的方法:

     var RAttribute = React.createClass({

        loadAssignmentsForList: function(elem) {
                //other code
            },

            render: function() {
                    var assignmentsLoading = this.props.assignmentsLoading;
                    var lists = this.props.data.lists.map(function(elem) {
                       return (<li className='list-group-item grey'>
                         <div className='list-group'>
                           <RList key = {elem.name} data={elem}
                              assignmentsLoading={assignmentsLoading}
                              loadAssignmentsForList={this.loadAssignmentsForList(elem)}/>
                       </div>
                      </li>);
                    });
                    //other code
          }
       //other code
     });

我正在尝试从render 中调用loadAssignmentsForList,所以我使用的是this.loadAssignmentsForList(elem)。但是,我收到以下错误。

Uncaught TypeError: Cannot read property 'loadAssignmentsForList' of undefined

【问题讨论】:

  • 你在转译 ES6 吗?如果是这样,您可以使用箭头功能。这真的取决于你的设置
  • 你提供的代码应该可以工作,一定是我们在那里看不到的东西
  • 虽然我的理解是 React 应该在 render 方法中自动绑定 this
  • 你的代码可以工作jsfiddle.net/69z2wepo/19357你能提供更多的代码
  • 我提供了更多代码。该错误实际上出现在 map 方法中。

标签: javascript reactjs


【解决方案1】:

.this绑定到.mapthis中的.map不引用RAttribute对象

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}.bind(this));

或者您可以通过第二个参数将this 设置为.map,像这样

var lists = this.props.data.lists.map(function(elem) {
   // your code             
}, this);

另外,如果你使用ES6,你可以使用arrow functions

var lists = this.props.data.lists.map((elem) => {
   // your code             
});

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多