目录
前言
实例期
存在期
销毁期
总结
前言
学习一门语言,他的生周期我们是必须要理解,在这里就给大家讲解一下我们平常最常用到的一些生命周期,希望能给各位带来帮助。
我们首先要知道,React的生命周期主要分为三部分:实例期(挂载期)、存在期(更新期)、销毁期(卸载)
实例期
getdefaultprops 获取默认的props
getinitailstate 获取初始的state
componentWillMount 组件即将挂载
componentWillMount(){
console.log('组件即将挂载')
}
render 渲染
render(){
console.log('开始渲染');
return (
<div> App </div>
)
}
componentDidMount 组件挂载完成
componentDidMount(){
console.log('组件挂载完成')
}
存在期
componentWillReceiveProps()
// 只在子组件中有效 当父组件传递给子组件(当前子组件)的值发生变化时执行
componentWillReceiveProps(nextProps){
console.log(nextProps)
}
//this.props 这个时候这个props依然是旧值
//nextProps 在这里的是新的props值
shouldComponentUpdate()
// 在子组件和父组件中都有效
// 当组件中props 或 state 任意一个值发生变化都会执行,返回的结果可以决定组件是否更新
shouldComponentUpdate(nextProps,nextState){
if(nextProps.num % 3 === 0){
return true // 可更新
}
return false // 不可更新
}
componentWillUpdate() 组件即将挂载
componentWillUpdate(nextProps,nextState){
console.log('组件即将挂载')
}
// nextProps,nextState 改变之后的值(新值)
componentDidUpdata() 组件挂载完成
componentDidUpdate(prveProps,prveState){
console.log('组件挂载完成')
}
// prveProps,prveState 改变之前的值(旧值)
销毁期
componentWillUnmount() 组件即将卸载 (组件卸载之前)
// 只在子组件中有效
componentWillUnmount(){
console.log('组件即将卸载')
// 组件卸载时清空该子组件里的点击事件
this.box.onclick = null
// 组件卸载时清空该组件里的定时器
clearInterval(this.timer)
}
总结
当然React 的生命周期有很多,但是我们常见的和常用的不过于就以上几个,在这里主要讲解了我们常用到的十个生命周期,当然想学习更多可查看官网 React生命周期——官网