React16 生命周期理解

完整生命周期

constructor(props) // 初始化参数

componentWillMount()

render() // 第一次渲染 

componentDidMount()

当父组件向子组件传入props发生改变后,依次调用

componentWillReceiveProps(nextProps)

shouldComponentUpdate(nextProps, nextState) 

componentWillUpdate()

render() //子组件更新渲染

componentDidUpdate()

当组件自身state发生变化后

componentWillUpdate()

render() //组件再次更新渲染

componentDidUpdate()

当组件卸载

componentWillUnmount()

生命周期详解

componentDidMount() 此处请求接口数据 
componentWillReceiveProps(nextProps) 子组件获得新props时触发,作用是在子组件再次渲染前,更新子组件自身的state,之后会触发shouldComponentUpdate()   
shouldComponentUpdate(nextProps, nextState) 接受的props发生变化或者自身state变化都会触发该生命周期,在此生命周期可以做一些渲染的优化,默认返回true,就是默认需要更新组件,重新渲染,nextProps nextState 都是新state 新props,this.props this.state 表示旧的props state,根据需求做优化,比如在某些情况下返回false,便不再进行组件更新了,提升页面性能
static getDerivedStateFormProps(nextProps, prevState)
替代 componentWillReceiveProps 返回的结果会送给setState 如果什么都不改变就返回null
static 声明静态函数,无法访问this,也就是一个纯函数,输出完全由输入决定
除了shouldComponentUpdate之外,render前的所有生命周期都被替代
返回新的state,重新进行setSate后,react会去控制不再进行新的更新
AJAX请求在依旧在componentDidMount 中进行,只有在一些特定情况下实用 (此处还未深入了解
貌似用的场景很少
eg: 
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log(nextProps); // 新传入的props
    console.log(prevState); // 旧的state
    //console.log(this.props);
    return {
      value: nextProps.value
    }
  }

例子

这个例子让你更好的理解几个生命周期的作用 Github地址在这里

图片描述

图片描述

参考react官方文档 State & 生命周期 && 性能优化 章节
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值