ReactNative的生命周期以运行时的状态来区分,可分为三类:
Mounting
Updating
- componentWillReceiveProps()
- shouldComponentUpdate()
- componentWillUpdate()
- render()
- componentDidUpdate()
Unmounting
当刚创建组件时,所调用方法的顺序如下:

当刷新组件时,所调用方法的顺序如下:

图中无componentWillReceiveProps方法的调用,是因为刷新时并未改变props对象。注意,组件初次被渲染时componentWillReceiveRrops方法并不会被触发。
props与state
声明Prop Types和Default Props
ES6
class Greeting extends Component {
// ...
}
Greeting.propTypes = { name: React.PropTypes.string};
Greeting.defaultProps = { name: 'Mary'};
ES5,getDefalutProps需要声明为函数
let Greeting = React.createClass({
propTypes: { name: React.PropTypes.string },
getDefaultProps: function() {
return { name: 'Mary' };
},
// ...});
初始化state
ES6
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
// ...
}
ES5,声明一个名为getInitialState的函数
let Counter = React.createClass({
getInitialState: function() {
return {
count: this.props.initialCount};
},
// ...
});
网友评论