3

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 'setState...' String will appear. But i don't understand the usage of this.setStateHandler.bind(this); function. Can anybody can explain it for me?

trungducng
  • 355
  • 6
  • 18
  • 2
    [Read this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) you should understand it. – Andrew Feb 24 '17 at 08:51

1 Answers1

9

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.

Deividas Karzinauskas
  • 6,243
  • 2
  • 25
  • 26
  • 1
    Please don't encourage questions like this by answering them. This has several duplicates on SOF and is very easy to google for other resources that explain it. Mark it as a duplicate and move on. – caesay Feb 24 '17 at 08:52
  • Sure, sorry about that :) still new. What's the best way to handle these questions? Do you just leave them unanswered? – Deividas Karzinauskas Feb 24 '17 at 08:53
  • Mark it as a duplicate (as a few of us have done) and it will get closed and link to that other question, which has lots of great answers already. – caesay Feb 24 '17 at 08:54
  • Ok. Was afraid of using flag :) Do I delete my answer? – Deividas Karzinauskas Feb 24 '17 at 08:55
  • You can leave your answer - don't flag it for moderator attention, if you don't have the reputation to mark it as a duplicate just hold on and soon you'll see a "close" button at the bottom of the question which you can use :) – caesay Feb 24 '17 at 08:56