生命周期函数指在某一时刻组件会自动调用执行的函数
生命周期图如下
// 在组件即将被挂载到页面上执行,只在第一次挂载到页面后执行
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请求获取数据
}
最后欢迎关注我的公众号,在这里我们聊的不止代码,还有人生,另外我还放置可平时个人觉得比较有用的一切前端资料在公众号,欢迎共享!