ES6课程中“this”的范围

时间:2015-07-09 09:07:26

标签: reactjs ecmascript-6 ecmascript-7

我很难理解this如何在ES6类中工作,这使得构建具有任何一致性的应用程序变得困难。以下是我在React类中混淆的一个例子:

class Class extends React.Component {

    constructor() {

        super();

        this.state = {
            timeout: 0
        }
    }

    componentWillMount() {

        // Register with Flux store.
        // On change run this._storeUpdated()
    }

    _storeUpdated() {

        if (this.state.timeout < 3) {
            console.log(this.state.timeout); // 0
            setTimeout(() => {
                this.setState({
                    authorized: false,
                    timeout: this.state.timeout + 1 // undefined?
                });
                // Force Flux store to update - re-runs this method.
            }, 1000)
        }
    }
}

为什么调用undefined中的this.state.timeout setState()?但是,如果我使用箭头函数,那么它可以工作:

_storeUpdated = () => {

    if (this.state.timeout < 3) {
        console.log(this.state.timeout); // 0
        setTimeout(() => {
            this.setState({
                authorized: false,
                timeout: this.state.timeout + 1 // 1
            });
            // Force Flux store to update - re-runs this method.
        }, 1000)
    }
}

这里到底发生了什么?

1 个答案:

答案 0 :(得分:3)

您可能会感到困惑,因为React在使用React.createClass时会进行自动绑定,但在从React.Component继承时(即ES6方式)则不会。 0.13 beta1 blog post

中解释了此更改

在您的具体情况下,由于您使用Flux.getStore('store').on('change', this._storeUpdated);,(method on EventEmitter3used by Flummox),因此上下文设置为EventEmitter对象,与您的组件对象无关,并且没有state属性。

注意,在注册事件监听器时,您可以指定this的值作为第三个参数:Flux.getStore('store').on('change', this._storeUpdated, <this-object>);

要在ES6类中实现自动查找,您应该使用React博客文章中描述的任何方法。作为旁注,如果您使用的是ES7,您甚至可以使用autobind decorator