【问题标题】:ReactJS TypeError: Cannot read property 'handleChange' of undefinedReactJS TypeError:无法读取未定义的属性“handleChange”
【发布时间】:2020-07-30 15:34:17
【问题描述】:

谁能解释一下为什么我在使用这种语法时会收到错误TypeError: Cannot read property 'handleChange' of undefined

const todoItems = this.state.todos.map(function(item) {
  return (
    <TodoItem
      key={item.id}
      item={item}
      handleChange={this.handleChange}
    />
  );
})

但是当我使用如下所示的箭头指针语法时没有错误

const todoItems = this.state.todos.map(
  item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>
)        

注意:在这两种情况下,我都在constructor() 中使用了this.handleChange = this.handleChange.bind(this)

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    区别在于this 是如何与 JS 中的函数一起工作的。这个解释来自this source

    在经典函数表达式中,this 关键字根据调用它的上下文绑定到不同的值。然而,对于箭头函数,这是词法绑定的。这意味着它使用了包含箭头函数的代码中的this。

    例如看下面的setTimeout函数:

    // ES5
    var obj = {
      id: 42,
      counter: function counter() {
        setTimeout(function() {
          console.log(this.id);
        }.bind(this), 1000);
      }
    };
    
    

    在 ES5 示例中,需要 .bind(this) 来帮助将 this 上下文传递给函数。否则,默认为undefined

    // ES6
    var obj = {
      id: 42,
      counter: function counter() {
        setTimeout(() => {
          console.log(this.id);
        }, 1000);
      }
    };
    

    ES6 箭头函数不能绑定到 this 关键字,因此它会在词法上上升一个作用域,并在定义它的作用域内使用 this 的值。

    Source to explanation

    【讨论】:

      【解决方案2】:

      您所指的是箭头函数表达式被引入 Javascript 的确切原因。 在 Javascript 中,每个函数都有一个定义“this”的范围。 这意味着:

      function f1() {
         this.name = "John";
         function f2() {
           // here this.name is undefined
           this.name = "Doe"
           // here this.name is "Doe"
      
         }
         // here this.name "John"
      }
      

      您可能想阅读 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

      【讨论】:

        【解决方案3】:

        你需要将你的map函数绑定到this,否则this是未定义的:

        const todoItems = this.state.todos.map(function(item){
            return (
                <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>
            )
        }.bind(this))
        

        【讨论】:

        • 你能解释一下为什么吗?因为我已经在构造函数this.handleChange = this.handleChange.bind(this) 中这样做了。或者这是别的什么?我在这里很新
        • @VishruthSubramanian 这是将组件的this 绑定到map 使用的匿名回调函数。如果您像任何其他类函数一样在组件外部定义映射回调,那么它更像是您如何在构造函数中将this 绑定到handleChange
        猜你喜欢
        • 2021-12-06
        • 2022-07-22
        • 2019-05-07
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        • 2021-12-28
        • 2021-11-18
        • 2020-04-20
        相关资源
        最近更新 更多