[英]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.