簡體   English   中英

ReactJS TypeError:無法讀取未定義的屬性“handleChange”

[英]ReactJS TypeError: Cannot read property 'handleChange' of undefined

有人可以解釋為什么我收到錯誤TypeError: Cannot read property 'handleChange' of undefined when I use this syntax

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)

您需要將 map function 綁定到this ,否則this是未定義的:

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

您所指的是箭頭函數表達式被引入 Javascript 的確切原因。 在 Javascript 中,每個 function 都有一個 scope 定義了“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

不同之處在於this如何與 JS 中的函數一起工作。 這個解釋來自這個來源

在經典的 function 表達式中, this關鍵字根據調用它的上下文綁定到不同的值。 然而,對於箭頭函數,這是詞法綁定的。 這意味着它使用了包含箭頭 function 的代碼中的 this。

例如,看下面的 setTimeout function:

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

在 ES5 示例中,需要 .bind(this) 來幫助將 this 上下文傳遞到 function。 否則,默認情況下這將是undefined

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

ES6 箭頭函數不能綁定到 this 關鍵字,所以它會在詞法上 go 向上一個 scope,並使用它在 scope 中定義的值。

解釋來源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM