React的生命周期

React的生命周期从广义上分为三个阶段:挂载、渲染、卸载

Mounting:已插入真实 DOM

Updating:正在被重新渲染

Unmounting:已移出真实 DOM

React的生命周期图:

1. 挂载卸载

constructor()、componentWillMount()、componentDidMount()、componentWillUnmount ()

2. 更新

componentWillReceiveProps (nextProps)

shouldComponentUpdate(nextProps,nextState)

componentWillUpdate (nextProps,nextState)

componentDidUpdate(prevProps,prevState)

render()

3. React新增的生命周期
getDerivedStateFromProps(nextProps, prevState) 
getSnapshotBeforeUpdate(prevProps, prevState)

getDerivedStateFromProps(nextProps, prevState)

代替componentWillReceiveProps()

componentWillReceiveProps(nextProps){
        let zyy= nextProps.zyy;
        this.setState({ a: zyy.a, b: zyy.b}) //更新state
    }
static getDerivedStateFromProps(nextProps, prevState) {
        const { a,b } = nextProps.zyy;
        if(a!== prevState.a){ //传入的props与state不同
            return {a:a,b:b} //将传入的props映射到state上
        }
        return null
    }

getSnapshotBeforeUpdate(prevProps, prevState)

代替componentWillUpdate
区别在于:

1、在 React 开启异步渲染模式后,在 render 阶段读取到的 DOM 元素状态并不总是和 commit 阶段相同,这就导致在componentDidUpdate 中使用 componentWillUpdate 中读取到的 DOM 元素状态是不安全的,因为这时的值很有可能已经失效了。

2、getSnapshotBeforeUpdate 会在最终的 render 之前被调用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值