justasking
justasking

Reputation: 105

Weird class property behaviour

I'm using React and bumped into something weird.

class C extends React.Component {

    componentDidMount = this.animate; // <---

    animate = () => ...

}

This did not work so I had to change the value of componentDidMount and it worked:

class C extends React.Component {

    componentDidMount = () => this.animate(); // Lambda is required?

    animate = () => ...

}

Does anyone have a good explanation as to why this is required?

Upvotes: 1

Views: 73

Answers (2)

t.niese
t.niese

Reputation: 40872

If you write

class C extends React.Component {
   componentDidMount = this.animate; // <---
   animate = () => ...
}

Then componentDidMount is set to undefined because animate is not set at that time.

With componentDidMount = () => this.animate(); the this.animate(); is resolved every time componentDidMount is called, that's why this does work for you.

If you write it that way:

class C extends React.Component {
   animate = () => ...
   componentDidMount = this.animate; // <---
}

Then componentDidMount will reference the function you assigned to animate before.

But if you want to define methods for a class you should check the answer of baao, because then you should not use the assignment but a method definition animate() {}

Upvotes: 2

baao
baao

Reputation: 73261

You should define the animate method as a class method, not as an arrow function.

class C extends React.Component {
    componentDidMount = this.animate;
    animate() {}
}

Upvotes: 2

Related Questions