[React] React组件的生命周期

注:
(1)componentDidMount只会在组件初始化的时候调用。
组件加载完后,再执行this.setState不会调用该方法,而是调用shouldComponentUpdate

(2)当父组件更新子组件属性的时候,所有子组件的componentWillReceiveProps(nextProps)会被调用。
即使当前子组件的props没有改变,组件的该方法也会被调用
该函数不返回布尔值,而是对比this.props(旧)与nextProps(新),通过this.setState更改组件状态。

Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.
——React.Component: componentWillReceiveProps()

(3)shouldComponentUpdate默认返回true
如果返回falsecomponentWillUpdate render componentDidUpdate方法就不被调用;
如果返回true,这些方法将被调用,React会通过diff算法更新DOM。

(4)以下流程是固定的,能影响流程的只有shouldComponentUpdate

// 当前组件和子组件shouldComponentUpdate都为true

Page: componentWillMount
Page: render
    A: componentWillMount
    A: render
    A: componentDidMount
Page: componentDidMount

Page: setState
Page: shouldComponentUpdate ---- true
Page: componentWillUpdate
Page: render
    A: componentWillReceiveProps
    A: shouldComponentUpdate ---- true
    A: componentWillUpdate
    A: render
    A: componentDidUpdate
Page: componentDidUpdate
// 子组件shouldComponentUpdate为false

Page: componentWillMount
Page: render
    A: componentWillMount
    A: render
    A: componentDidMount
Page: componentDidMount

Page: setState
Page: shouldComponentUpdate ---- true
Page: componentWillUpdate
Page: render
    A: componentWillReceiveProps
    A: shouldComponentUpdate ---- false
Page: componentDidUpdate
// 当前组件的shouldComponentUpdate为false

Page: componentWillMount
Page: render
    A: componentWillMount
    A: render
    A: componentDidMount
Page: componentDidMount

Page: setState
Page: shouldComponentUpdate ---- false

参考

Component Specs and Lifecycle

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容