react生命周期新旧对比

react生命周期16.0前的生命周期

首次进去页面执行的生命周期钩子函数有:(初始化阶段和挂载阶段)

1.constructor (初始化数据,也可以super(props) 调用基类的构造方法 props只读不可变,state可变)

2.componentWillMount ( 在组件挂载到DOM前调用 )

3.render ( 不负责组件实际渲染工作,之后由React自身根据此元素去渲染出页面DOM )

4.componentDidMount ( 组件挂载到DOM后调用,且只会被调用一次,一般会在这个钩子函数中做一些初始化的事情,例如:开启定时器,发送网络请求,订阅消息 )

更新阶段:(一般由组件的内部this.setState()或者父组件render触发)

 

1.组件自身调用setState更新

1.shouldComponentUpdate(注意:如果使用强制更新this.forceUpdate(),不会触发该生命周期)

( 当更新时无论数据是否变化都调用,优化:可以使用回调参数(nextProps,nextState)更新之后的数据来比较是否需要更新,false就不render,true继续更新)

//控制组件更新的“阀门”
            shouldComponentUpdate(nexrProps,nextStates){
                if(nextStates.count == this.state.count) return false
                console.log('Count---shouldComponentUpdate');
                return true
            }

2.componentWillUpdate

· 此方法在调用render方法前执行,在这边可执行一些组件更新发生前的工作,一般较少用。

3.render

4.componentDidUpdate( prevProps, prevState )

· 此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState这两个参数指的是组件更新 的props和state

2.父组件重新render或者父组件传的props的值变化

componentWillReceiveProps ( nextProps )

·nextProps 是父祖件传入的新增值,可以根据传入值更新子组件的状态。

//这种方式十分适合父子组件的互动,通常是父组件需要通过某些状态控制子组件渲染亦或销毁...
 
componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一个参数代表即将传入的新的Props
    if (this.props.sharecard_show !== nextProps.sharecard_show){
        //在这里我们仍可以通过this.props来获取旧的外部状态
        //通过新旧状态的对比,来决定是否进行其他方法
        if (nextProps.sharecard_show){
            this.handleGetCard();
        }
    }
}

shouldComponentUpdate

componentWillUpdate

render

componentDidUpdate

 

react16.0以后的生命周期

1624514620238

首次进入页面初始化的生命周期 (去除了componentWillMount)

constructor

static getDerivedStateFromProps (nextProps,prevState) 用来代替( componentWillReceiveProps )

两者的参数是不相同的,而getDerivedStateFromProps是一个静态函数,也就是这个函数不能通过this访问到class的属性,也并不推荐直接访问属性。而是应该通过参数提供的nextProps以及prevState来进行判断,根据新传入的props来映射到state。

//若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps
static getDerivedStateFromProps(nextProps, prevState) {
    const {type} = nextProps;
    // 当传入的type发生变化的时候,更新state
    if (type !== prevState.type) {
        return {
            type,
        };
    }
    // 否则,对于state不进行任何操作
    return null;//必写否则报错
}

render

componentDidMount

 

更新阶段生命周期

getDerivedStateFromProps

shouldComponentUpdate(注意:如果使用强制更新this.forceUpdate(),不会触发该生命周期)

render

getSnapshotBeforeUpdate

componentDidUpdate

总结:

1.React16新的生命周期弃用了componentWillMount、componentWillReceivePorps,componentWillUpdate

2.新增了getDerivedStateFromProps、getSnapshotBeforeUpdate来代替弃用的三个钩子函数(componentWillMount、componentWillReceivePorps,componentWillUpdate)

react更新生命周期原因:https://www.zhihu.com/question/278328905

不停学习,热爱是源源不断的动力。
原文地址:https://www.cnblogs.com/ximenchuifa/p/14926689.html