Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js and arrow functions vs normal functions [duplicate]

I was working on a react.js app and I initially used the arrow function which worked, but then just out of curiosity I decided to try the normal function and the normal function didn't work. I think that they both should output the same thing, what is going wrong?

handleChange = event => this.setState({init: event.target.value})

handleChange(event){
  this.setState({init: event.target.value})
}
like image 564
deBhailis Avatar asked Dec 03 '22 19:12

deBhailis


1 Answers

Arrow functions and normal function are not equivalent.

Here is the difference:

  1. Arrow function do not have their own binding of this, so your this.setState refer to the YourClass.setState.

  2. Using normal function, you need to bind it to the class to obtain Class's this reference. So when you call this.setState actually it refer to YourFunction.setState().

Sample Code

class FancyComponent extends Component {
    handleChange(event) {
        this.setState({ event }) // `this` is instance of handleChange
    }

    handleChange = (event) => {
        this.setState({ event }) // `this` is instance of FancyComponent
    }
}
like image 54
I Putu Yoga Permana Avatar answered Dec 06 '22 12:12

I Putu Yoga Permana