javascript - react /ES6 : Arrow Function not binding "this" as expected

标签 javascript reactjs ecmascript-6 leaflet arrow-functions

语言:React/JavaScript ES6

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

涉及的其他图书馆:传单

问题:

在上下文 this 下的函数绑定(bind)到 我需要的组件。

之前:

componentDidMount: function() {

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

    }

但是当我将其切换为使用我预期的箭头功能时 等效绑定(bind),但是 this 更改为传单类 o.Class.extend.e - 未定义 this.setState

之后:

componentDidMount: function() {

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

}

问题:为什么使用箭头函数不等同于 在我的情况下绑定(bind)this

最佳答案

遇到了同样的问题。原来 Babel-loader(在我的例子中使用预设 '@babel/preset-env')并没有像预期的那样将箭头函数绑定(bind)到它。

在我的 webpack 配置中使用这个插件添加了正确的绑定(bind)

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

关于javascript - react /ES6 : Arrow Function not binding "this" as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155688/

相关文章:

javascript - D3.js饼图逆向动画

javascript - 带有管理面板和客户端面板的 MEAN 应用程序

javascript - antd react 中有没有解决方法来检查组件中未保存的更改?

javascript - ES6 支持 Elvis 运算符吗?

javascript - 在现有对象中声明异步函数

javascript - JQuery、CSS 和对话框。将东西插入按钮 Pane div

javascript - 函数覆盖类而不是添加新的

javascript - × TypeError : Cannot read properties of undefined (reading 'getState' )

javascript - 如何不变地更改或更新状态的特定值

javascript - ES6 Javascript : Calling static methods from classes with arrow functions