Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.56 KB | None | 0 0
  1. class People extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. people:[{ name: "mary", age: 25 }, { name: "john", age: 30 }]
  6. };
  7. }
  8.  
  9. updateJohnAge = ()=>{
  10. const people = [...this.state.people];
  11. people[1].age=31;
  12. this.setState({people});
  13. //This will not work.
  14. //People is a new array, but john is the same object
  15. }
  16.  
  17. render() {
  18. return (
  19. <div>
  20. <Person person={this.state.people[1]}></Person>
  21. <button onClick={this.updateJohnAge}>Set john age to 31</button>
  22. </div>
  23. );
  24. }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement