React Native 组件生命周期

getInitialState()

组件在安装之前,会调用 getInitialState 来初始化组件的状态,返回值被用作 this.state 的初始值来使用。

注意:在 ES6 中,使用下面方式设置初始化值:

1
2
3
4
5
6
7
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}

getDefaultProps()

在创建类的时候调用并缓存,如果该组件没有从父组件获得到 props,可以通过这个方法设置默认值。这个组件创建的值不能够跨实例共享,不会被赋值。

注意:在 ES6 中,可以使用下面的方式设置默认值:

1
2
3
4
5
6
7
class Greeting extends React.Component {
// ...
}

Greeting.defaultProps = {
name: 'Mary'
};

propTypes

propTypes 对象能够验证传递给组件的 props 的类型:

1
2
3
4
5
6
7
8
9
10
11
12
propTypes: {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
// more ...
}

更多详细信息可参考这里

componentWillMount()

函数原型:

1
void componentWillMount()

这个方法是在组件创建并初始化之后,在第一次 render() 之前调用,可以做一些业务初始化操作,也可以设置㢟状态。这个函数在整个生命周期中只被调用一次

componentDidMount()

函数原型:

1
void componentDidMount()

组件第一次 render() 之后,只会调用一次。可以再这个函数中操作子组件。需要注意的是,React Native 是先调用子组件的 componentDidMount() ,然后在调用父组件的函数。可以在这个组件当中设置计时器或者网络请求等。调用这个函数完毕后,就等待触发其他事件。

componentWillReceiveProps()

函数原型:

1
2
3
void componentWillReceiveProps(
object nextProps
)

当组件收到新的 props,就会调用该函数。举个例子:

1
2
3
4
5
6
7
// nextProps 是即将被设置的新的属性,旧的属性还可以通过 this.props 来获取。
// 根据属性的变化,通过 this.setState() 来更新组件状态、这里面更新状态是安全的,并不会触发额外的 render()
componentWillReceiveProps(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}

shouldComponentUpdate()

函数原型:

1
2
3
boolean shouldComponentUpdate(  
object nextProps, object nextState
)

当组件接收到新的 propsstate 改变的话,会触发调用该方法。参数 nextPropscomponentWillReceiveProps 函数一样。参数 nextState 表示组件即将更新的状态值。返回参数决定是否需要更新组件,如果 true 表示更新,继续向下执行。否则表示不更新,直接进入等待状态。

默认情况下,该函数永远返回 true 来保证数据变化的时候 UI 能同步更新,也可以通过检查属性变化前后来决定 UI 是否更新来提高应用性能。

componentWillUpdate()

函数原型:

1
2
3
void componentWillUpdate(
object nextProps, object nextState
)

shouldComponentUpdate 函数返回 true,并且 nextProps 或者 nextState 发生改变时,就会开始更新组件。

注意:这个方法里面不能调用 this.setState() 来修改状态,这个函数调用之后,就会把 nextPropsnextState 分别设置到 this.propsthis.state 中。紧接着这个函数,就会调用 render() 来更新界面了。

componentDidUpdate()

函数原型:

1
2
3
void componentDidUpdate(  
object prevProps, object prevState
)

这里已经完成 props 和 state 状态的更新,此函数的输入参数就变成了 prevPropsprevState

componentWillUnmount()

函数原型:

1
void componentWillUnmount()

组件销毁的时候调用,可以做一些组件相关的清理工作,例如取消计时器等。


参考:
https://race604.com/react-native-component-lifecycle/