React:this.state在for循环中消失

时间:2015-04-08 14:35:04

标签: javascript reactjs

如何将this带入我的.map()循环?它似乎消失了。 : - (

我正在制作一个动态表格"用户可以为其表单指定多行输入。我想迭代state.items[]中的所有项目并为它们构建表单输入字段。

例如,表格以'字段'开头。和' autocomplete_from。然后,用户可以点击添加新行以在表单中获得更多行。

102     render: function() {
103       return (
104         <div>
105           {this.state.items.map(function(object, i){
106             return (
107               <div>
109                 <FieldName/>

110                 <strong> State.autocomplete_from:
                            {this.state.autocomplete_from} </strong>
                         //       ^^^ 
                         //   Uncaught TypeError: Cannot read property 'state' of undefined

120                 <button onClick={this.newFieldEntry}>Create a new field</button>
121                 <button onClick={this.saveAndContinue}>Save and Continue</button>
122               </div>
123               );
124           })}
125         </div>
126       );

4 个答案:

答案 0 :(得分:13)

.map 未引用您的组件。有多种方法可以解决此问题

  1. this保存到变量

    render: function() {
      var _this = this;
    
      return (
       <div>
         {this.state.items.map(function(object, i){
           return (
             <div>
               <FieldName/>
    
               <strong> State.autocomplete_from:
                 {_this.state.autocomplete_from} </strong>
    
               <button onClick={this.newFieldEntry}>Create a new field</button>
               <button onClick={this.saveAndContinue}>Save and Continue</button>
             </div>
           );
         })}
       </div>
     );
    }
    
  2. this回调设置.map,如果您无法使用ES2015功能,则首选此变体

    this.state.items.map(function (object, i) {
       // ....
    }, this);
    
  3. 使用arrow function

    this.state.items.map((object, i) => {
       // ....
    }) 
    
  4. 使用.bind

    this.state.items.map(function(object, i) {
       // ....
    }.bind(this)) 
    

答案 1 :(得分:0)

mapfilter等迭代方法的第二个参数是this对象

所以你可以按如下方式使用它:

this.state.items.map(yourfunction,this)

答案 2 :(得分:0)

调用函数时。这是设置为全局对象,除非它是您正在调用的成员方法,或者您使用.call.apply进行调用,而不是您的情况。

或者换句话说,你不能关闭this,但是你可以更接近你为此分配的标准变量。所以一般来说,如果你有一个嵌套在另一个函数中的函数,你希望参考这个:

function outer(){
   var _this = this;
   someThingThatAcceptsACallback(function(){
      console.log(_this.state);
   }
}

答案 3 :(得分:0)

如果您正在使用Babel或其他现代EcmaScript6-&gt; JS5编译器,则可以使用更简单的语法来保留外部上下文的上下文:

{
     this.state.items.map((object, i) => {
         return ( <div>
              <strong> State.autocomplete_from:
                  {this.state.autocomplete_from} 
              </strong>
              /*.... your code ...*/ </div>); 
     });
}

通过使用箭头函数语法,this上下文自动绑定在包含的函数中,因此您可以使用this,因为您不需要在您的任何内容中执行任何特殊操作代码。