When you call {this.addUser} , it is called, here this is an instance of your class (component), and therefore it does not give you any error, since the addUser method exists in your scope class, but when you are under the addUser method, you use this to update state , which exist in the scope of the component (component), but you are currently within the addUser method, and therefore it gives you an error, since in the addUser Scope section you have nothing like state, user, etc. d. Therefore, to solve this problem, you need to bind this while you call the addUser method. So your method always knows an instance of this .
So, the final change in your code will look like this: -
<Form addUser={this.addUser.bind(this)}/>
OR <h / "> You can bind this in the constructor, because this is the place when you should evaluate things, because the constructor methods are called first when the components display the DOM .
So you can do it like this: -
constructor(props) { super(props); this.state = { users: null } this.addUser=this.addUser.bind(this); }
And now you can call it the usual way, as you did before: -
<Form addUser={this.addUser}/>
I hope this works, and I let you know.
Vinit raj
source share