React has one way data flow.
So when you want to pass child component's data (a new dog) back to the parent (which is the one that maintains the list of dogs), you pass a callback to the child component, which will call the handler with the newly created dog object.
Simply put, this.props.addDog passes form data back to App component.
I've spotted a bug in App.handleAddDog, in which you are mutating the this.state.dogs by pushing the dog to the state directly.
You should not mutate the state object directly as React would not know if the this.state.dogs has not changed.
create a copy (a new reference of dogs) and set it as a new state.
handleAddDog(dog){// This will create a copy of `this.state.dogs`const{dogs}=this.state;// or you can doconstdogs={...this.state.dogs};// then push the `dog` to the new dogs state objectdogs.push(dog);// Now `dogs` has a new reference and React will re-render `Dogs` componentthis.setState({dogs:dogs});}
The reason for passing a new reference of dogs is an advanced concept on how React reconciles changes.
Simply put, it's for React not having to do deep property change checks
If you want to know more on how React reconcilation diff'ing algorithm works, check out this post.
Yes. I think you got it.
React has one way data flow.
So when you want to pass child component's data (a new dog) back to the parent (which is the one that maintains the list of dogs), you pass a callback to the child component, which will call the handler with the newly created dog object.
Simply put,
this.props.addDog
passes form data back toApp
component.I've spotted a bug in
App.handleAddDog
, in which you are mutating thethis.state.dogs
by pushing the dog to the state directly.You should not mutate the state object directly as React would not know if the
this.state.dogs
has not changed.So instead of
create a copy (a new reference of dogs) and set it as a new state.
The reason for passing a new
reference
ofdogs
is an advanced concept on how React reconciles changes.Simply put, it's for React not having to do deep property change checks
If you want to know more on how React reconcilation diff'ing algorithm works, check out this post.
css-tricks.com/how-react-reconcili...