您的位置:首页 > Web前端 > React

react生命钩子的执行顺序

2020-01-13 23:58 357 查看

React的生命周期钩子跟Vue有些相似

初始化阶段
Vue: beforeCreate、created、beforeMount、mounted
React:constructor、componentWillMount【旧】、render、componentDidMount

运行阶段:【可能会执行多次】
Vue:beforeUpdate、updated
React:
state变化:shouldComponentUpdate、componentWillUpdate【旧】、render、componentDidUpdate
props变化:componentWillReceiveProps【旧】、shouldComponentUpdate、componentWillUpdate【旧】、render、componentDidUpdate

卸载阶段:
Vue:beforeDestory destoryed
React:componentWillUnmount

以上带【旧】的都是即将废除的钩子


父组件传给子组件中的数据发生改变

子组件内部渲染数据发生改变,生命钩子的执行顺序

页面有dom销毁,生命钩子执行顺序

父组件

import React,{Component} from "react";

// 导入子组件
import Old from '../life/Old'

class Index extends Component{
state={
age:18,
isShow:true
}
render(){
return <div>
<Old age={this.state.age}/>
<button onClick={()=>{this.setState({age:this.state.age+1})}}>点我改变</button>
<button onClick={()=>{this.setState({isShow:false})}}>点我隐藏div</button>

{this.state.isShow && <Old />}
</div>
}
}
export default Index

子组件

import React ,{Component} from "react";

export default class Old extends Component{
constructor(props){
super()
console.log('----constructor---');
this.state={
name:'xi'
}
}
componentWillMount(){
console.log('---componentWillMount----');

}
render(){
console.log('-----render----');

return <div>
这是一个寂寞的天
<p>{this.props.age}</p>
<button onClick={()=>{this.setState({name:'小可爱'})}}>点击改name</button>
<p>name:{this.state.name}</p>
</div>
}

componentDidMount(){
console.log('---componentDidMount---');
}

componentWillReceiveProps(nextProps){
console.log('----componentWillReceiveProps---');
console.log(nextProps);
}

shouldComponentUpdate(){
console.log('---shouldComponentUpdate----');
return true  //为false将不改变视图层,后面的钩子都不执行
}

componentWillUpdate(){
console.log('+---componentWillUpdate--');

}
componentDidUpdate(){
console.log('---componentDidUpdate---');

}
componentWillUnmount(){
console.log('----componentWillUnmount----');

}
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
考拉菜鸟 发布了15 篇原创文章 · 获赞 0 · 访问量 571 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: