When you call {this.addUser}
, it gets called, here this
is an instance of your class(component), and thus it gives no error to you because addUser
method does exist in your class scope
,
but when you are under addUser
method you are using this
to update the state
which exist in
the scope of class(component), but currently you are within the scope of addUser
method and so it gives you an error as under addUser
Scope you got nothing like state, user etc.
So to deal with this problem you need to bind this
while you are calling addUser
method.So that your method always knows the instance of this
.
So the final change in your code will look like this:-
<Form addUser={this.addUser.bind(this)}/>
OR
You can bind
this
in the constructor,because it is the place when you should intialize things because constructor methods are called first when the components render to the
DOM
.
So you can do it in this way:-
constructor(props) {
super(props);
this.state = {
users: null
}
this.addUser=this.addUser.bind(this);
}
And now you can call it in normal way as you did before:-
<Form addUser={this.addUser}/>
I hope this will work,And I made it clear to You.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…