Search code examples
reactjsredux

what is the usage of : this.method.bind(this)


I'm studying Reactjs and have a block of code like this:

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
        
      this.state = {
         data: []
      }
    
      this.setStateHandler = this.setStateHandler.bind(this);
   };

   setStateHandler() {
      var item = "setState..."
      var myArray = this.state.data;
      myArray.push(item)
      this.setState({data: myArray})
   };

   render() {
      return (
         <div>
            <button onClick = {this.setStateHandler}>SET STATE</button>
            <h4>State Array: {this.state.data}</h4>
         </div>
      );
   }
}

export default App;

After click button, the 'SET STATE' String will appear. But i don't understand the usage of this.setStateHandler.bind(this); function. Can anybody can explain it for me?


Solution

  • this.setStateHandler().bind(this) sets the context for the function setStateHandler() to be the class object. This is necessary so that you could call this.setState({...}) inside the method, because setState() is the method of React.Component. If you do not .bind(this) you would get an error that setState() method is undefined.