简体   繁体   English

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

[英]React.js, how to avoid var me = this?

wondering about the best way to avoid using var me = this; 想知道避免使用var me = this的最佳方法; in the following context. 在以下背景下。 This method exists inside of a React component. 此方法存在于React组件内。 I have used the underscore.js method _.bind() in the past - is there a more reacty way? 我过去曾使用过underscore.js方法_.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
    },

Preserving the correct this is more a JavaScript problem than React. 保留正确的this问题比React更像是一个JavaScript问题。

1) One option is to use the .bind() method: 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
    },

The .bind(this) will create a new function that has the same this as the findRoutes() function. .bind(this)将创建具有相同的新函数thisfindRoutes()函数。

2) Another option from ES6 is the arrow function : 2)ES6的另一个选项是箭头功能

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

The arrow function will take lexically this from the findRoutes() . 箭头功能将词汇采取thisfindRoutes()

See this article for more details about this keyword. 有关this关键字的更多详细信息, 请参阅此文章

My tip to avoid the need of referencing this on the context is start using ES6 's arrow functions 我的提示是避免在上下文中引用它,这是开始使用ES6箭头函数

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). 与函数表达式相比,箭头函数表达式具有更短的语法,并且词汇绑定此值(不绑定它自己的this,arguments,super或new.target)。 Arrow functions are always anonymous. 箭头功能始终是匿名的。

So you could use a arrow function as the promise callback. 所以你可以使用箭头函数作为promise回调。

let p1 = new Promise((resolve, reject) => {
    resolve(this.state)
})

The best way in my opinion of using ES6 in your React project is using Babel for compiling the ES6 code and Webpack for module bundling. 我认为在您的React项目中使用ES6的最佳方法是使用Babel编译ES6代码和使用Webpack进行模块捆绑。

Here is a good example of project to start using webpack and babel: 以下是开始使用webpack和babel的项目的一个很好的例子:

https://github.com/choonkending/react-webpack-node https://github.com/choonkending/react-webpack-node

您可以使用箭头函数 ,该函数提供与值的词法绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM