简体   繁体   中英

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

Language: React/JavaScript ES6

Bundling Tool: 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.

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.

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?

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.

Using this plugin in my webpack config added the correct binding

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

Made some changes :
Arrow functions do not bind the this keyword. That's how they work. If you need to use this keyword, you need to use the bind function. 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));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM