7.08.1 Component Update Lifecycle In Action
- Convert from functional to class-based components
- Add Update Lifecycle
Person.js
Person.js
import React, { Component } from "react";
import classes from "./Person.css";
class Person extends Component {
render() {
console.log("[Person.js] rendering...");
return (
<div className={classes.Person}>
<p onClick={this.props.click}>
I'm {this.props.name} and I am {this.props.age} years old!
</p>
<p>{this.props.children}</p>
<input
type="text"
onChange={this.props.changed}
value={this.props.name}
/>
</div>
);
}
}
export default Person;
Persons.js
Persons.js
import React, { Component } from "react";
import Person from "./Person/Person";
class Persons extends Component {
// static getDerivedStateFromProps(props, state) {
// console.log("[Persons.js] getDerivedStateFromProps");
// return state;
// }
// componentWillReceiveProps(props) {
// console.log("[Persons.js] componentWillReceiveProps", props);
// }
shouldComponentUpdate(nextProps, nextState) {
console.log("[Persons.js] shouldComponentUpdate");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("[Persons.js] getSnapshotBeforeUpdate");
return { message: "Snapshot!" };
}
// componentWillUpdate() {
// }
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("[Persons.js] componentDidUpdate");
console.log(snapshot);
}
render() {
console.log("[Persons.js] rendering...");
return this.props.persons.map((person, index) => {
return (
<Person
click={() => this.props.clicked(index)}
name={person.name}
age={person.age}
key={person.id}
changed={(event) => this.props.changed(event, person.id)}
/>
);
});
}
}
export default Persons;