繁体   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