so I've recently started to learn react from Udemy, I wrote this code which dynamically changes the state of the page when a button is clicked. The tutor has the same code and his code works perfectly fine but mine doesn't. May I know what's wrong?
Here is my App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person';
class App extends Component {
state = {
persons: [
{name : 'Honey', age : 23},
{name : 'Test', age: 19},
{name : 'Test2', age: 21}
],
otherState : 'Hmm'
}
//edit
switchPersonHandler = () => {
this.setState = ( {
persons: [
{name : 'Honey', age : 23},
{name : 'Ahhh', age: 19},
{name : 'Change this', age: 21}
]
} )
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React :)</h1>
</header>
<button onClick={this.switchPersonHandler}>Switch Name</button>
<Person name={this.state.persons[0].name} age={this.state.persons[0].age}/>
<Person name={this.state.persons[1].name} age={this.state.persons[1].age}/>
<Person name={this.state.persons[2].name} age={this.state.persons[2].age}/>
</div>
);
}
}
export default App;
Here is my persons.js
import React from 'react'
const person = (props) => {
return <div>
<p>My name is {props.name} and my age is {props.age}</p>
</div>
}
export default person;
So, what I want to do is when t he button is clicked, they persons object gets dynamically merged and updated content is showed on the web page. Also, pardon me if this is a bad question, I'm really new to this.
this.setState({ persons: [...] })