React Native开发经验集React Native开发react-native开发

react-native 的生命周期

2018-04-17  本文已影响108人  mark666

前言

在面试的时候被偶尔问到了react-native 的生命周期的问题,以前确实研究过这个过程,但是时间久了给忘了,一时语噎竟然一个完整的函数名字没说出来,当时恨不得拿出我的电脑看一下这个过程,然后根据自己的思路娓娓道来,可惜还是记不起来了,正好成这个机会总结一下,下方这张图已经完美诠释了

react-native生命周期

如上我们可以将组件的生命周期分为以下三个阶段:

这里需要强调和解释以下几点:

constructor(props) {
      super(props);
          //设置一些初始值
      this.state = {
      };
}

这里super(props)是必须调用的. 这个跟旧RN版本是有区别的,我们不再用关注getDefaultProps getInitialState 这些过时的方法。

componentWillReceiveProps(nextProps)

我发现有很多人在问,这个方法为什么不调用,我们可以看一段这个方法的解释:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

只有当组件接收到新的属性值的时候才能触发这个方法。

其次当我们设置了this.setState()设置了某些属性值的变化,调用顺序是

以上就是react native 生命周期,大家可以试验一下这个过程来加深这个过程。

我给大家准备了一个demo,可以下载下来验证:
https://github.com/markdashi/ReactNativeLife.git

希望看到这篇文章的伙伴,不要盗取本人绘制的流程图,如需要转载最好注明出处,谢谢!

上一篇 下一篇

猜你喜欢

热点阅读