总结react生命周期

553 阅读1分钟

react_旧.jfif

constructor和render不算生命周期,为了更好显示程序加载顺序放在一起排序。

一、旧生命周期

    // 初始化阶段  由React.render触发,--初次渲染
    1constructor(props)
    2componentWillMount()
    3render()
    4componentDidMount()  // 一般做初始化的事,例如开启定时器,发请求,订阅消息
    
    // 更新阶段 由组件内部this.setDate或父组件render触发
    1componentWillReceiveProps()
    2shouldComponentUpdate()
    3componentWillUpdate()
    4render()
    5componentDidUpdate()
    
    // 卸载阶段  由ReactDOM.unmountComponentAtNode()触发
    1componentWillUnmount()  // 一般做收尾的事情

二、新版兼容

去掉3个钩子,新版使用需要加 UNSAFE_
    componentWillMount
    componentWillReceiveProps
    componentWillUpdate

三、新生命周期

react_新.jfif

    // 初始化阶段: 由ReactDOM.render()触发---初次渲染
    1constructor()                                      构造器
    2、getDerivedStateFromProps            state的值在任何时候都取决于props
    3render()
    4componentDidMount()                 

    // 更新阶段: 由组件内部this.setSate()或父组件重新render触发
    1、getDerivedStateFromProps      
    2shouldComponentUpdate()             控制组件更新的“阀门”
    3render()
    4、getSnapshotBeforeUpdate             在更新之前获取快照
    5componentDidUpdate(preprops,prestate,napshotValue) 组件更新完毕的钩子
    // 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
    1componentWillUnmount()              组件将要卸载的钩子      

四、新加入两个生命周期讲解(官网说基本不用)

    static getDerivedStateFromProps(props){
        return props || null
    }
    
    返回一个状态对象或者null
    state任何时候值都取决于props,组件传入!
    getSnapshotBeforeUpdate(){
        return any
    }
    
    返回snapshot value或者null
    dom发生渲染之前,从dom中捕获信息,返回值作为参数传递给componentDidUpdate
    
    componentDidUpdate(preprops,prestate,napshotValue)

五、常用生命周期

    render
    componentDidMount
    componentWillUnmount