React 学习笔记 之 生命周期

react 声明周期分三个状态: 初始化 更新 销毁。

一、初始化

1、getDefaultProps()

     设置默认的props,在使用es6的class语法时是没有这个钩子函数的会报错。

Warning: getDefaultProps was defined on LifeCircle, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.

2、getInitialState()

      在使用es6的class语法时是没有这个钩子函数的,可以直接在constructor中定义this.state。此时可以访问this.props

3、componentWillMount()

      组件初始化时调用,组件更新时不调用,整个生命周期只调用一次,此时可以修改state

4、render()

      react最重要的步骤,创建虚拟dom,进行diff运算,更新dom树都在此进行,此时不能更改state了。

       如果更改state,会报错

Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

5、componentDidMount()

     组件渲染之后调用,只调用一次

二、更新

1、componentWillReceiveProps(nextProps)

      组件初始化时不调用,组件接受新的props时调用。

2、shouldComponentUpdate(nextProps, nextState)

      react性能优化非常重要的一环。组件接受新的state或者props时调用,我们可以设置在此对比前后两个props和state是否相同,如果相同则返回false阻止更新,因为相同的属性状态一定会生成相同的dom树,这样就不需要创造新的dom树和旧的dom树进行diff算法对比,节省大量性能,尤其是在dom结构复杂的时候

3、componentWillUpdate(nextProps, nextState)

     组件初始化时不调用,只有在组件将要更新时才调用,此时可以修改state

4、render()

     组件渲染

5、componentDidUpdate()

      组件初始化时不调用,组件更新完成后调用,此时可以获取dom节点。

三、销毁 

1、componentWillUnmount()

     组件将要卸载时调用,一些事件监听和定时器需要在此时清除。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值