react native 生命周期详解

2018-06-20  本文已影响0人  sybil052

React Native严格定义了组件的生命周期,可能经历如下三个阶段:

IMG_20180620_143932.jpg

生命周期各个函数

constructor

ES6中每个类的构造函数,并不是每个组件都需要定义自己的构造函数,需要构造函数往往有以下目的:

  1. 初始化state
    组件生命周期中任何函数都有可能要访问state,整个生命周期第一个被调用的constructor函数自然是初始化state最理想的地方;
  2. 绑定成员函数的this环境
    在ES6语法下,类的每个成员函数在执行时的this并不是和类实例自动绑定的。在构造函数中,this就是当前组件实例,为了方便未来调用,往往在构造函数中将这个实例的特定函数绑定this为当前实例。
getDefaultProps

getDefaultProps这个函数的返回值可以作为props的初始值,但是这个方法只有用React.createClass方法创建组件类才会用到。

getInitialState

getInitialState这个函数的返回值会用来初始化组件的this.state,但是这个方法只有用React.createClass方法创建组件类才会发生作用。

componentWillMount

componentWillMount会在render函数之前被调用,通常不用定义componentWillMount函数,在componentWillMount中做的事情可以提前到constructor中去做。

render

组件渲染,是React Native组件中最重要的函数。

componentDidMount

组件渲染完成会调用componentDidMount。

componentWillReceiveProps

组件接收到新的props,会调用componentWillReceiveProps。在这个函数里面,你可以根据属性的变化,通过调用 this.setState() 来更新你的组件状态,这里调用更新状态是安全的,并不会触发额外的 render() 调用。

注:父组件的render函数被调用,在render函数里面的子组件就会经历更新过程,不管父组件传给子组件的props有没有改变,都会触发子组件的componentWillReceiveProps函数。

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate决定了一个组件什么时候不需要渲染,该函数返回一个布尔值,如果返回true,就会继续更新过程,返回false,就会立刻停止更新过程。默认情况下,这个函数永远返回 true 用来保证数据变化的时候 UI 能够同步更新。在大型项目中,你可以自己重载这个函数,通过检查变化前后属性和状态,来决定 UI 是否需要更新,能有效提高应用性能。

注:通过this.setState函数引发更新过程,并不是立刻更新组件的state值,在执行到shouldComponentUpdate时,this.state依然是this.setState函数执行之前的值,我们需要做的就是在nextProps,nextState,this.state,this.props中互相比对。

componentWillUpdate

在这个函数中,可以做一些在更新界面之前要做的事情。

需要特别注意的是,在这个函数里面,不能使用 this.setState 来修改状态。这个函数调用之后,就会把 nextProps 和 nextState 分别设置到 this.props 和 this.state 中。

componentDidUpdate

调用了 render方法更新完成界面之后,会调用 componentDidUpdate方法。

componentWillUnmount

当组件要被从界面上移除的时候调用。

总结表格

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

猜你喜欢

热点阅读