简体   繁体   English

React/ES6:箭头函数未按预期绑定“this”

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

Language: React/JavaScript ES6语言:React/JavaScript ES6

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

Other Libs Involved : Leaflet其他涉及的库:传单

Problem:问题:

With the function below the context this is bound to the component as I need.使用上下文下方的函数, this将根据我的需要绑定到组件。

Before:之前:

componentDidMount: function() {

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

    }

But when I switched it over to using the arrow function I expected an equivalent binding, but this changed to a leaflet Class o.Class.extend.e - leaving this.setState undefined.但是,当我换过来使用箭头功能我预计等效约束力,但this改变为单张类o.Class.extend.e -离开this.setState不确定的。

After:之后:

componentDidMount: function() {

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

}

Question: Why is using the arrow function not the equivalent of binding this in my case?问题:为什么在我的例子中使用箭头函数不等同于绑定this

Had the same issue.有同样的问题。 Turns out the Babel-loader (in my case using the preset '@babel/preset-env') does not bind the arrow function to this as one would expect.结果是 Babel-loader(在我的例子中使用预设的 '@babel/preset-env')并没有像人们期望的那样将箭头函数绑定到这个。

Using this plugin in my webpack config added the correct binding在我的 webpack 配置中使用这个插件添加了正确的绑定

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

Made some changes :做了一些改变:
Arrow functions do not bind the this keyword.箭头函数不绑定this关键字。 That's how they work.他们就是这样工作的。 If you need to use this keyword, you need to use the bind function.如果需要使用this关键字,就需要使用bind函数。 Also using bind with arrow function can be weird.使用带有箭头函数的绑定也可能很奇怪。 You might need to do something like this :你可能需要做这样的事情:

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