What is the difference between func () => {} and func = () => {} in a class?

I am now studying the syntax Classfor creating React components and notice that now I need to declare methods like this:

class Foo extends React.Component {
    ...
    bar = () => {
        this.setState({ ... })
    }    
}

instead of this:

class Foo extends React.Component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}

or i can't use this.setState().

Can someone explain what the difference is between creating similar methods and how they relate to the function prototype?

+4
source share
2 answers

, , Stage 3 , , . ( ), (, , this). :

class Foo extends React.component {
    constructor() {
        this.bar = () => {
            this.setState({ ... })
        };
    }
}

- , prototype, "" this (, this , ).

this : , bar , this ( , ); this ( , , ).

+8

:

class Foo extends React.component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}

this , :

class Foo extends React.component {
    constructor(props) {
       super(props);
       this.bar = this.bar.bind(this);
    }

    bar() {
        this.setState({ ... })  // works
    }
}
0

Source: https://habr.com/ru/post/1689442/


All Articles