Skip to content

React的生命周期 #34

Description

@incuisting

当一个React组件被 mount(挂载) 的时候,会经过以下几个生命周期:
constructor => componentWillMount => render => componentDidMount

当状态或者属性触发了一次更新,当一个组件在被重渲时,这些方法将会被调用:
componentWillReceiveProps => shouldComponentUpdate => componentWillUpdate => render => componentDidUpdate

当一个组件被从DOM中移除时,该方法被调用:
componentWillUnmount

以上是react官方文档的描述
看一张图深入理解
image

可以看出,当组件的state发生改变的时候。会先去看shouldComponentUpdate,如果true,那么就componentWillUpdate => render => componentDidUpdate 完成更新。
但是如果改变是来自props,那么会先经过componentWillReceiveProps,然后再去看shouldComponentUpdate是不是为true,为truecomponentWillUpdate => render => componentDidUpdate

不过有意思的是,如果shouldComponentUpdate 这个生命周期你不去刻意的设置它默认就是true,也就是你这个组件就是没有变化也会被再渲染一次,会在性能上造成很大的浪费。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions