gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:52:02 24 4
gpt4 key购买 nike

语言: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com