react的生命周期

生命周期函数指在某一时刻组件会自动调用执行的函数

生命周期图如下

react的生命周期

// 在组件即将被挂载到页面上执行,只在第一次挂载到页面后执行

componentWillMount(){

console.log('componentWillMount')

}

//页面挂载之后执行

componentDidMount(){

console.log('页面挂载之后执行')

}

 

//组件更新之前,会被自动执行

shouldComponentUpdate(){ //要求我们返回一个boolean值

console.log('shouldComponentUpdate')

return true

}

//组件被更新之前,会被自动执行,但是在shouldComponentUpdate之后执行

componentWillUpdate(){

console.log('shouldComponentUpdate')

}

//组件被更新之后

componentDidUpdate(){

console.log('componentDidUpdate')

}

//当一个组件从父组件接收了一个参数

//如果这个组件第一次存在于父组件中,不会执行

//如果这个组件不是第一次存在于父组件中,会执行

componentWillReceiveProps() {

console.log('componentWillReceiveProps')

}

//当这个组件即将被页面剔除的时候会被执行

componentWillUnmount(){

console.log('componentWillUnmount')

}

生命周期使用场景

 

shouldComponentUpdate(nextProps,naxtSate){ //提升了组件的性能,避免组件去做无谓的渲染

if (nextProps.content!== this.props.content){

return true

}else{

return false

}

}

 

componentDidMount(){

//ajax请求获取数据

}