每个生物都有它自己的生命周期,从出生、少年、成年再到死亡。同理,组件也有它特定的生命周期,React用不同的方法来描述它的整个生命周期。
下面是定义一个react组件的结构:
import React, { Component } from 'react';
class Test extends Component {
constructor(props, context) {
super(props, context)
this.state = {
//定义state
}
}
componentWillMount() {}
componentDidMount() {}
componentWillReceiveProps(nextProps) {}
shouldComponentUpdate(nextProps, nextState) {}
componentWillUpdate(nextProps, nextState) {}
componentDidUpdate(prevProps, prevState) {}
render() {
return(
<div></div>
)
}
componentWillUnmount() {}
}
export default Demo;
下面进行各生命周期的详解:
生命周期
1)getDefaultProps: 在装载之前调一次,在组件中赋值的数据会被设置到this.props中;
2)getInitialState: 调用在装载之前,这个函数的返回值会被设置到this.state中。在ES6的写法中,只需写在constructor中即可;
class Demo extends Component {
constructor(props, context) {//只要组件存在constructor,就必须要写super,否则this指向会错误
super(props, context)
this.state = {
//定义state
}
}
}
3)componentWillMount: 在render之前被调用,可以在渲染前做一些准备工作(一般用在服务端渲染);
4)componentDidMount: 组件第一次渲染完成,此时dom节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染;
5)componentWillReceiveProps: 在接受父组件改变后的props需要重新渲染组件时用到的比较多,它接收一个nextProps参数,通过对比nextProps和this.props,将nextProps setState设置为当前的state,从而重新渲染组件;
6)shouldComponentUpdate: 在重新render之前被调用,会返回一个Boolean值,false时为阻止组件的更新;注:因为react父组件重新渲染会导致其所有子组件的重新渲染,这个时候我们可能并不需要左右的子组件跟着重新渲染,因此需要在子组件的该生命周期中做判断;
7)componentWillUpdate:在render调用之前,可以渲染一些准备工作,当 shouldComponentUpdate返回true时,组件进入重新渲染的过程;
8)render: render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧dom树,比较之后,找到最小的有差异的dom节点,并会重新渲染;
9)componentDidUpdate: 组件更新完成后立即调用,可以拿到更新前的props和state;
10)componentWillUnmount: 组件卸载,可以做一些清理工作。如:clear组件中的setTimeout、setInterval;移除组件中的监听removeEventListener