React 5 生命周期

React 5 生命周期

生命周期简介

组件的生命周期分成三个状态:

  • Mounting:已插入真实 DOM

  • Updating:正在被重新渲染

  • Unmounting:已移出真实 DOM

React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。

  • componentWillMount()
    • componentDidMount()
    • componentWillUpdate(object nextProps, object nextState)
    • componentDidUpdate(object prevProps, object prevState)
    • componentWillUnmount()

此外,React 还提供两种特殊状态的处理函数。

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
    • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

react生命周期流程

  1. 初始化, 首次render

    • getDefaultProps() 用来设置组件属性的默认值,在组件被建立时候就立即调用,所有实例都可以共享这些属性。

    • getInitialState() 用于定义初始状态,也不可以使用this.state和setState。

    • componentWillMount() 只在初始化时候被调用一次,可以使用setState方法,会立即更新state,然后接着进行render。

    • render() 特别注意此方法里面不可以使用setState。如果其中包含其他的子组件,那么子组件的生命周期才开始进行。

    • componentDidmount() 在子组件也都加载完毕后执行,在react中DOM渲染完成,此时才可以操作dom。(如果需要通过id,class选取dom时,在此方法里使用)。

      1. props发生改变时更新
    • componentWillReceiveProps(nextProps)

    componentWillReceiveProps方法可以比较this.props和nextProps来看是否发生了变化,然后可以进行setState等操作。

    注意只要父组件此方法触发,那么子组件也会触发,也就是说父组件更新,子组件也会跟着更新。

    • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在接收了新的props或state后触发,你可以通过返回true或false来控制后面的生命周期流程是否触发。

    • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在props或state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。

    • render()

    重新渲染。

    • componentDidupdate(prevProps, prevState)

    会等子组件也都更新完后才触发。

    1. state发生改变时候更新

      • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在setState后state发生改变后触发,你可以通过返回true或false来控制后面的生命周期流程是否触发。

    • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。

    • render()

    重新渲染。

    • componentDidupdate(prevProps, prevState)

    会等子组件也都更新完后才触发。


使用redux时候情况

在使用redux做状态管理时候,基本不需要透过生命周期去做setState这样的状态管理了,基本都是用props来传递来重新渲染,需要注意的仅仅是在哪个生命周期时候触发action,比如需要进行ajax请求时候一般都是在componentDidMount和componentWillReceiveProps时候进行,在reducer中处理完,然后在通过props传入组件执行组件的更新周期。


参考资料

  1. 阮一峰react入门实例

  2. react生命周期总结

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值