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

Javascript React.js,如何避免var me=this?,javascript,reactjs,binding,this,Javascript,Reactjs,Binding,This,想知道避免使用var me=this的最佳方法;在下面的上下文中。此方法存在于React组件内部。我过去使用过underline.js方法uz.bind()——有没有更具反应性的方法 findRoutes: function(){ var me = this; if (!this.state.originId || !this.state.destinationId) { alert("findRoutes!");

想知道避免使用var me=this的最佳方法;在下面的上下文中。此方法存在于React组件内部。我过去使用过underline.js方法uz.bind()——有没有更具反应性的方法

    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
    },

保留正确的
与其说是反应,不如说是JavaScript问题

1) 一种选择是使用以下方法:

arrow函数将从
findrootes()
中以词汇形式获取此


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

我的建议是使用的开始

与函数表达式相比,箭头函数表达式的语法更短,并且在词汇上绑定this值(不绑定自己的this、arguments、super或new.target)。箭头函数总是匿名的

因此可以使用arrow函数作为promise回调函数

let p1 = new Promise((resolve, reject) => {
    resolve(this.state)
})
在我看来,在React项目中使用ES6的最佳方法是编译ES6代码和进行模块绑定

下面是一个很好的开始使用webpack和babel的项目示例:

您可以使用提供对值的词汇绑定的

 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
    },
let p1 = new Promise((resolve, reject) => {
    resolve(this.state)
})