1Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.
2
3Mounting – Birth of your component
4Update – Growth of your component
5Unmount – Death of your component
1class Clock extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {date: new Date()};
5 }
6
7 componentDidMount() { }
8 componentWillUnmount() { }
9 render() {
10 return (
11 <div>
12 <h1>Hello, world!</h1>
13 <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
14 </div>
15 );
16 }
17}
1class Test extends React.Component {
2 constructor() {
3 console.log('Constructor')
4 super();
5 this.state = {
6 count: 0
7 };
8 }
9
10 componentDidMount() {
11 console.log("component did mount");
12 }
13 componentDidUpdate() {
14 console.log("component did update");
15 }
16
17 onClick = () => {
18 this.setState({ count: this.state.count + 1 });
19 };
20 render() {
21 console.log("render");
22 return (
23 <div>
24 Hello Test
25 <button onClick={this.onClick}>
26 {this.state.count}
27 </button>
28 </div>
29 );
30 }
31}
32
33
34//--for first time
35//Constructor
36//render
37//component did mount
38//--for any update
39//render
40//component did update
1INITIALIZATION= setup props and state
2MOUNTING= constructor->componentWillMount->render->componentDidMount//Birth
3UPDATE= shouldComponentUpdate->componentWillUpdate->render
4 ->componentDidUpdate //Growth
5UNMOUNTING= componentWillUnmount //Death
1class Content extends React.Component {
2 // ...
3 componentWillMount() {
4 this.setState({ activities: data });
5 }
6 // ...
7}
8
1class ActivityItem extends React.Component {
2 render() {
3 const { activity } = this.props;
4
5 return (
6 <div className='item'>
7 <div className={'avatar'}>
8 <img
9 alt='avatar'
10 src={activity.actor.avatar_url} />
11 </div>
12
13 <span className={'time'}>
14 {moment(activity.created_at).fromNow()}
15 </span>
16
17 <p>{activity.actor.display_login} {activity.payload.action}</p>
18 <div className={'right'}>
19 {activity.repo.name}
20 </div>
21 </div>
22 )
23 }
24}
25