[关闭]
@wrlqwe 2016-04-24T17:14:32.000000Z 字数 1835 阅读 1081

React Native组件的生命周期

react-native 开发


前言

与Native的开发一样,React Native上有相似的生命周期,在程序运行的某个确定的时间点执行。下面根据不同阶段进行介绍。

组件加载前

getDefaultProps

object getDefaultProps()
在组件类创建的时候调用一次,然后返回值被缓存下来。这个方法在实例创建之前调用,因此不能依赖于 this.props。另外,getDefaultProps() 返回的任何复杂对象将会在实例间共享,而不是每个实例拥有一份拷贝。

组件的加载和初始化

getInitialState

object getInitialState()
在组件挂载之前调用一次。返回值将会作为 this.state 的初始值。

componentWillMount

componentWillMount()
在组件创建初始化状态之后调用,可以在此做一些初始化操作,或者设置组件状态,以备接下来的第一次render()

componentDidMount

componentDidMount()
这个函数调用的时候,DOM 已经构建完成,你可以在这个函数开始获取其中的元素或者子组件了。需要注意的是,RN 框架是先调用子组件的 componentDidMount(),然后调用父组件的函数。从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求。这个函数之后,组件的初始化正式完成,开始等待事件触发。

组件的运行阶段

componentWillReceiveProps

componentWillReceiveProps(object nextProps)
如果组件收到新的属性(props),就会调用 componentWillReceiveProps(), nextProps 是即将被设置的属性,旧的属性可以通过 this.props 来获取。在这个回调函数里面,你可以根据属性的变化,通过调用 this.setState() 来更新你的组件状态,这里调用更新状态是安全的,并不会触发额外的 render() 调用。

对于 state,没有相似的方法: componentWillReceiveState()。将要传进来的 prop 可能会引起 state 改变,反之则不然。如果需要在 state 改变的时候执行一些操作,请使用 componentWillUpdate。

shouldComponentUpdate

boolean shouldComponentUpdate(object nextProps, object nextState)
在接收到新的 props 或者 state 时,开发者来决定是否渲染。
默认情况下这个方法返回true, 即始终渲染。
在开发复杂组件时,重写这个方法可以提升性能。

componentWillUpdate

componentWillUpdate(object nextProps, object nextState)
如果组件状态或者属性改变,并且上面的 shouldComponentUpdate() 返回为 true,就会开始准更新组件,并在 render() 前调用 componentWillUpdate()
在这个函数里面,不能使用 this.setState() 来修改状态。如果需要更新 state 来响应某个 prop 的改变,可以使用 componentWillReceiveProps()

componentDidUpdate

componentDidUpdate(object prevProps, object prevState)
调用了 render() 更新完成界面之后,会调用 componentDidUpdate() 来得到通知。

组件卸载阶段

componentWillUnmount

componentWillUnmount()
在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注