React Native组件生命周期

组件生命周期:实例化、挂载、渲染、更新、卸载、销毁

挂载的周期:

constructor(object props)

组件被实例化,构造函数props参数由于初始化组件熟悉,props由创建该组件的父元素指定的。这个时候组件还没渲染。

componentWillMount()

在组件第一次渲染前被调用,只会被调用一次。这个时候组件还没被渲染。

render() -> React Element

组件渲染。这个方法必须返回一个React元素,或者返回null表示不渲染任何东西。

componentDidMount()

在组件第一次渲染后被调用,只会被调用一次。这个时候组件被渲染完成。一般异步请求或者setTimeout延时耗时操作是在这个方法里面完成的。

更新的周期:

componentWillReceiveProps(object nextProps)

组件的父元素传递进来新的熟悉nextProps,该组件将会重新渲染。你可以调用setState()方法在render渲染之前来更新该组件的内部状态。

shouldComponentUpdate(object nextProps, object nextState) -> boolean

该方法决定组件要不要真正重新渲染。默认实现是返回true表示重新渲染。为了优化,你可以重写该方法,判断props和state是否改变了,来决定是否需要重新渲染。返回false将不会重新渲染,也就是render方法不会被调用。

componentWillUpdate(object nextProps, object nextState)

当shouldComponentUpdate()方法返回true时,接着这个方法就会被调用。这个时候调用this.setState()等方法没有用了,因为渲染已经开始了。

render() -> React Element

当shouldComponentUpdate()方法返回true时,这个方法就会被调用,重新渲染组件。这个方法必须返回一个React元素,或者返回null表示不渲染任何东西。

componentDidUpdate(object prevProps, object prevState)

重新渲染完成之后,这个方法被调用。