簡體   English   中英

React/ES6:箭頭函數未按預期綁定“this”

[英]React/ES6: Arrow Function not binding “this” as expected

語言:React/JavaScript ES6

打包工具:Webpack(babel-loader 6.0.0)

其他涉及的庫:傳單

問題:

使用上下文下方的函數, this將根據我的需要綁定到組件。

之前:

componentDidMount: function() {

     map.on('draw:created', function(e){
        this.setState({someProp:propUpdate});
        featureGroup.addLayer(e.layer);
     }.bind(this));

    }

但是,當我換過來使用箭頭功能我預計等效約束力,但this改變為單張類o.Class.extend.e -離開this.setState不確定的。

之后:

componentDidMount: function() {

    map.on('draw:created', (e) => {
        this.setState({someProp:propUpdate});
        featureGroup.addLayer(e.layer);
    });

}

問題:為什么在我的例子中使用箭頭函數不等同於綁定this

有同樣的問題。 結果是 Babel-loader(在我的例子中使用預設的 '@babel/preset-env')並沒有像人們期望的那樣將箭頭函數綁定到這個。

在我的 webpack 配置中使用這個插件添加了正確的綁定

plugins: [
  ['@babel/plugin-transform-arrow-functions', { 'spec': true }]
]

做了一些改變:
箭頭函數不綁定this關鍵字。 他們就是這樣工作的。 如果需要使用this關鍵字,就需要使用bind函數。 使用帶有箭頭函數的綁定也可能很奇怪。 你可能需要做這樣的事情:

componentDidMount: function() {
    var thisKey = this;
    map.on('draw:created', (e) => {
        this.setState({someProp:propUpdate});
        featureGroup.addLayer(e.layer);
    }.bind(thisKey));

}

暫無
暫無

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

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