constructor:
1、主要做初始化工作,在调用当前函数的时候必须在内部调用super,否则this指向会发生错误
2、可以定义当前组件所需要用到的状态值,使用 this.state={},进行存放
3、在这个生命周期函数中想要获取props(外部数据)需要在super中继承
constructor(props){
super(props)
}componentWillMount:挂载前
1、在这个里面可以接收外部数据,将外部数据转化外内部数据
2、尽量不要使用setState,因为当前生命周期执行完毕后就会指向render(渲染)
3、用来做数据最后的渲染
在 react17 中已废除
render:渲染
1、当 this.setState/this.props 发生改变的时候 render 函数就会执行
2、render 函数每次执行的时候会将虚拟 DOM 在缓存中缓存一份,当下次 render 函数执行的时候,会与缓存中的虚拟 DOM 进行对比(这种对比时diff算法)将发生改变的虚拟 DOM进行行更新
componentDidMount:挂载后
1、当前生命周期我们可以通过 this.refs 来获取真实的 DOM 结构,通过 this.refs.属性名 或 者 在标签中 ref={(属性名)=>{this.属性名}=(属性名)} 下方直接this.属性名就可以
2、在这里一般做 ajax 请求
shouldComponentUpdate:
1、当前生命周期必须有一个返回值,返回 true 继续执行下面的生命周期,返回 false 则不会执行下面的生命周期
2、在这里面我们可以做性能优化,如果当前数据改变后没有必要进行render渲染,可以返回一个 return false,需要渲染则返回 return true 从而减少不必要的渲染
3、这里面有俩参数,一个新的 props 一个新的 state,当前生命周期主要决定 render 函数是否渲染,而不是数据是否更新
componentWillUpdate:更新前
1、在这里做数据最后的更新处理
2、当前函数中有两个参数 一个新的 props 一个新的 state
componentDidUpdate:更新后
1、数据更新完毕,获取到最新的 DOM 结构
2、当前函数中有俩参数,一个旧的 props 一个旧的 state
componentWillReceiveProps:
1、当 this.props 发生改变的时候,这个函数就会执行,有一个参数 新的 props 可以用来做外部数据的处理
render 函数什么时候执行?
当 this.props/this.setState 发生改变的时候
组件第一次执行的时候会执行哪些生命周期?
constructor(初始化) --> componentWillMount(挂载前) --> render(渲染)-->componentDidMount(挂载后)
哪些生命周期函数只执行一次?
constructor、componentWillMount、componentDidMount、componentWillUnmount
哪些生命周期执行多次?
render、componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentDidUpdate
当this.state/this.props发生改变的时候会执行哪些生命周期函数?
this.state(内部数据):shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate
this.props(外部数据):componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate