I
I
Ivan2019-08-19 15:23:13
JavaScript
Ivan, 2019-08-19 15:23:13

Why do react regularly use the bind method?

I don’t understand why a hard binding to the context is used, if the object itself does not carry anything, please explain on your fingers.
here is an example

class FriendsContainer extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      name: 'Tyler McGinnis',
      friends: [
        'Jake Lingwall',
        'Sarah Drasner',
        'Merrick Christensen'
      ],
    }

    this.addFriend = this.addFriend.bind(this)
  }
  addFriend(friend) {
    this.setState((state) => ({
      friends: state.friends.concat([friend])
    }))
  }
  render() {
    return (
      <div>
        <h3> Name: {this.state.name} </h3>
        <AddFriend addNew={this.addFriend} />
        <ShowList names={this.state.friends} />
      </div>
    )
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-08-19
@BenderIsGreat34

In your example, so that in the this.setState call, this points to your component, not undefined.
Now in React development, instead of calling the constructor and bind, it is customary to use class properties:

class Example extends React.Component {
  state = {
    someProp: '',
  };

  someHandler = () => {
    this.setState({ someProp: 'someValue' });
  };

  render() { ... }
}

D
Demian Smith, 2019-08-19
@search

People of antiquity tied the method to the context in this way. In ancient times, there were no arrow functions.
In your example, we are passing a function this.addFriendto the event handler addNew. JS is designed in such a way that when you pass this.addFriend (anywhere, even to a handler, even to a variable), then only addFriend without this will be passed. Bind is just needed in order to nail the FriendsContainer to the context of the addFriend method.
In the modern world, it is customary to do this:

class FriendsContainer extends React.Component {
  addFriend = (friend) = >{
    this.setState((state) => ({
      friends: state.friends.concat([friend])
    }))
  }
}

This is essentially the same bind, only without unnecessary gestures.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question