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