React生命周期

React16.3.0之前生命周期

创建期:

constructor(props)
componentWillMount()
render()
componentDidMount()

运行时:

props发生变化时
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)
state发生变化时
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState)

卸载时

componentWillUnmount()

React16.3.0之后的生命周期

创建期:

constructor(props)
getDerivedStateFromProps(props, state) //静态方法 static
render()
componentDidMount()
//或者如下生命周期:

constructor(props)
componentWillMount() / UNSAFE_componentWillMount() //前者会有警告⚠️
render()
componentDidMount()

getDerivedStateFromProps/getSnapshotBeforeUpdatecomponentWillMount/componentWillReceiveProps/componentWillUpdate如果同时存在,React会有警告信息,并且只执行 getDerivedStateFromProps/getSnapshotBeforeUpdate【React@16.3.0(以后)】

运行时:

props发生变化时
getDerivedStateFromProps(props, state) //静态方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)

// 或者如下生命周期:

componentWillReceiveProps()/UNSAFE_componentWillReceiveProps()//前者会有警告⚠️
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
render()
componentDidUpdate(prevProps, prevState, snapshot)
state发生变化时
getDerivedStateFromProps(props, status) //静态方法 static
shouldComponentUpdate(nextProps, nextState, nextContext)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)
或者如下生命周期:

shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate()/UNSAFE_componentWillUpdate()//前者会有警告⚠️
render()
componentDidUpdate(prevProps, prevState, snapshot)

销毁时

componentWillUnmount()
图示生命周期

static getDerivedStateFromProps(props, state)

当组件的state和props发生改变的时候会在 render() 前会被执行

该方法有两个参数props和state;

class SomeView extends Component {
    state = {
        count: 20
    }
    static getDerivedStateFromProps(props, state) {
        return {
            count: 50
        }
    }
    render() {
        return (
            <div>{this.state.age}</div>
        )
    }
}

这个方法允许组件基于 props 的变更来更新其内部状态,以这种方式获得的组件状态被称为派生状态。应该谨慎使用派生状态,可能会引入潜在的错误

getSnapshotBeforeUpdate(prevProps, prevState)

在render()的输出被渲染到DOM之前被调用。使组件能够在它们被更改之前捕获当前值(如滚动位置)。这个生命周期返回的任何值都将作为第三个参数传递给componentDidUpdate()

父组件子组件初始化示意图(网图)
父组件发生改变示意图(网图)
卸载组件示意图(网图)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 挂载阶段 (使用 class 的方式) constructor 组件挂载之前,会调用它的构造函数,通常在这个阶段会...
    阿畅_阅读 418评论 0 2
  • getDefaultProps 执行过一次后,被创建的类会有缓存,映射的值会存在this.props,前提是这个p...
    G_whk阅读 2,239评论 0 0
  • 一、写在前面 接触react已有几个月的时间,根据自己的经验总结一下对react生命周期的理解。本文将结合人的一生...
    DiffY阅读 360评论 0 0
  • componentWillMount 1 .在渲染之前调用,在客户端也在服务器端2 .正确调用的时候是在compo...
    skoll阅读 285评论 0 0
  • 彩排完,天已黑
    刘凯书法阅读 4,281评论 1 3