生命周期函数是指在某一时刻组件会自动调用的函数。
比如 render 函数就是一个生命周期函数。当 state 和props 发生改变的时候,就会被重新执行。
constructor 函数,是在组件创建的时候会被调用。按理说也符合生命周期函数的定义,但是它并不是React独有的函数,它是ES6规定的写法。
对一个React组件来说,它会经历如下几个过程,初始化,挂载(有三个周期函数),更新,去除。
componentWillMount 生命周期函数,是在组件即将被挂载到页面的时候自动执行。
componentDidMount 生命周期函数,是在组件被挂载到页面之后自动执行。
componentWillMount() {
console.log('hihihi')
}
componentDidMount() {
console.log('被挂载了')
}
shouldComponentUpdate 生命周期函数,是在组件被更新之前会执行。
shouldComponentUpdate() {
console.log('shouldComponentUpdate')
return true
}
componentWillUpdate 生命周期函数,在组件被更新之前执行,它在shouldComponentUpdate 之后执行,后者返回true前者才可以执行。(当子组件,已存在与父组件之中才会生效)
componentWillUpdate() {
console.log('componentWillUpdate')
}
componentDidUpdate 生命周期函数,在组件更新完成之后会被执行。
componentWillReceiveProps 生命周期函数,当一个组件从父组件接收了参数,只要父组件的render函数被执行了,子组件的componentWillReceiveProps 函数就会被执行。
componentWillUpdate() {
console.log('child componentWillUpdate')
}
componentWIllUnmount 生命周期函数,当一个组件即将从页面去除的时候会被调用。
componentWillUnmount() {
console.log('componentWillUnmount')
}