gpt4 book ai didi

javascript - React.js,如何避免 var me = this?

转载 作者:行者123 更新时间:2023-11-30 11:57:57 26 4
gpt4 key购买 nike

想知道避免使用 var me = this 的最佳方法;在以下上下文中。此方法存在于 React 组件内部。我过去使用过 underscore.js 方法 _.bind() - 有没有更 react 灵敏的方法?

    findRoutes: function(){
var me = this;
if (!this.state.originId || !this.state.destinationId) {
alert("findRoutes!");
return;
}
var p1 = new Promise(function(resolve, reject) {
directionsService.route({
origin: {'placeId': me.state.originId},
destination: {'placeId': me.state.destinationId},
travelMode: me.state.travelMode
}, function(response, status){
if (status === google.maps.DirectionsStatus.OK) {
// me.response = response;
directionsDisplay.setDirections(response);
resolve(response);
} else {
window.alert('Directions config failed due to ' + status);
}
});
});
return p1
},

最佳答案

保留正确的 this 比 React 更像是一个 JavaScript 问题。

1) 一种选择是使用 .bind()方法:

 findRoutes: function(){
if (!this.state.originId || !this.state.destinationId) {
alert("findRoutes!");
return;
}
var p1 = new Promise(function(resolve, reject) {
directionsService.route({
origin: {'placeId': this.state.originId},
destination: {'placeId': this.state.destinationId},
travelMode: this.state.travelMode
}, function(response, status){
//...
});
}.bind(this)); // <----------- .bind(this)
return p1
},

.bind(this) 将创建一个与 findRoutes() 函数具有相同 this 的新函数。

2) ES6 的另一个选项是 arrow function :

 findRoutes: function(){
if (!this.state.originId || !this.state.destinationId) {
alert("findRoutes!");
return;
}
var p1 = new Promise((resolve, reject) => { // <------- used =>
directionsService.route({
origin: {'placeId': this.state.originId},
destination: {'placeId': this.state.destinationId},
travelMode: this.state.travelMode
}, function(response, status){
//...
});
});
return p1
},

箭头函数将从 findRoutes() 中按词法获取 this

See this article有关 this 关键字的更多详细信息。

关于javascript - React.js,如何避免 var me = this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37406849/

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