Answer the question
In order to leave comments, you need to log in
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
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() { ... }
}
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.addFriend
to 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])
}))
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question