React Native(RN)-组件生命周期

生命周期简介

像 Android 开发一样,React Native(RN) 中的组件也有生命周期(Lifecycle)。

React Native(RN)-组件生命周期_第1张图片
借用他人流程图
(借用大神流程图)
这张图很简洁直观地告诉我们,生命周期的整个流程以及阶段划分。

第一阶段

getDefaultProps -> getInitialState -> componentWillMount ->render ->componentDidMount。 事实上,每个组件都会经历这个流程生命周期,是一个组件创建跟加载的过程。
getDefaultPropsgetInitialState是对state跟props的初始化和设置,当然现在比较流行的写法,是直接在contructor构造器中直接对这两个状态进行设置
compinentWillMount:该方法可以进行一些业务的初始化,或者订阅RN广播。特别注意的是,在整个生命周期中,该方法只会被调用一次。
render,渲染方法,绝对不能在该方法调用改变状态的的方法(setState)!
componentDidMount:主要作用是通知组件已经加载完成。需要注意的是,RN 框架是先调用子组件的 componentDidMount() ,然后调用父组件的函数。该方法在整个生命周期中也是只调用一次!

第二阶段

运行中 ->属性(props)改变( 父层界面发生改变) ->componentWillReceiveProps->shouldComponentUpdate—true—>componentWillUpdate->render->componentDidUpdate ->运行中。当然还有运行中—(状态发生改变)—>shouldComponentUpdate-…, 该过程发生在用户界面交互过程中。
componentWillReceiveProps:如果组件收到新的属性(props),就会调用该方法。在这个回调函数里面,你可以根据属性的变化,通过调用 this.setState() 来更新你的组件状态,这里调用更新状态是安全的,并不会触发额外的 render() 调用。
shouldComponentUpdate:默认情况下,这个函数永远返回 true 用来保证数据变化的时候 UI 能够同步更新
componentWillUpdate:其函数原型:void componentWillUpdate(object nextProps, object nextState),在这个方法中,可以做一些在更新界面之前要做的东西。不过在这里面,你就不能使用 this.setState 来修改状态。这个函数调用之后,就会把 nextProps 和 nextState 分别设置到 this.props 和 this.state 中。这个函数执行完,紧接着就会调用 render() 来更新界面了。
componentDidUpdate:调用了 render() 更新完成界面之后,会调用 componentDidUpdate() 来得到通知

第三阶段

卸载前->componentWillUnmount ->结束
componentWillUnmount:当组件要被从界面上移除的时候,就会调用该方法,可以在该方法中做一些清理的工作,比如清除RN广播,清除数据等

总结

生命周期                                  调用次数                   能否使用setSate()
getDefaultProps                          1(全局调用一次)                 否
getInitialState                          1                             否
componentWillMount                       1                             是
render                                   >=1                           否
componentDidMount                        1                             是
componentWillReceiveProps                >=0                           是
shouldComponentUpdate                    >=0                           否
componentWillUpdate                      >=0                           否
componentDidUpdate                       >=0                           否
componentWillUnmount                     1                             否

如果觉得此文不错,麻烦帮我点下“喜欢”。么么哒!

你可能感兴趣的:(React Native(RN)-组件生命周期)