Advertisement
Guest User

Untitled

a guest
May 24th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. diff --git a/src/App.js b/src/App.js
  2. index 2f38698..b54bb3f 100644
  3. --- a/src/App.js
  4. +++ b/src/App.js
  5. @@ -13,14 +13,20 @@ class App extends Component {
  6. showPersons: false
  7. };
  8.  
  9. - nameChangedHandler = (event) => {
  10. - this.setState({
  11. - persons: [
  12. - {name: "Max", age: 25},
  13. - {name: event.target.value, age: 30},
  14. - {name: "Sarah", age: 35}
  15. - ]
  16. + nameChangedHandler = (event, id) => {
  17. + const personIndex = this.state.persons.findIndex(p => {
  18. + return p.id === id;
  19. });
  20. + //Since we don't want to change state directly (since a Person is a ref.)
  21. + // we create a copy of the person using the spread operator with the person
  22. + //object. ... copies everything to the new object
  23. + const person = {...this.state.persons[personIndex]};
  24. + person.name = event.target.value;
  25. +
  26. + const persons = [...this.state.persons];
  27. + persons[personIndex] = person;
  28. +
  29. + this.setState({persons: persons});
  30.  
  31. };
  32.  
  33. @@ -35,8 +41,8 @@ class App extends Component {
  34. //and here we are not changing the pointer; we are changing the value
  35. //it points to.
  36. newPersons.splice(personIndex, 1);
  37. - this.setState({persons:newPersons})
  38. - }
  39. + this.setState({persons: newPersons})
  40. + };
  41.  
  42. togglePersonsHandler = () => {
  43. const doesShow = this.state.showPersons;
  44. @@ -64,6 +70,7 @@ class App extends Component {
  45. name={aPerson.name}
  46. age={aPerson.age}
  47. key={aPerson.id}
  48. + changed={(event)=>this.nameChangedHandler(event, aPerson.id)}
  49. />
  50. })}
  51. </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement