前言
眼看很多公司都開始嘗試使用ReactNative,達(dá)到跨平臺(tái)開發(fā),最近也寫了很多文章,希望讓更多想了解的同學(xué)快速上手ReactNative.
如果喜歡我的文章,可以關(guān)注我微博:袁崢Seemygo
ReactNaive組件生命周期
- 任何一個(gè)組件都是有生命周期的,我們經(jīng)常需要在組件的生命周期中做一些事情,比如創(chuàng)建組件的時(shí)候或者組件銷毀的時(shí)候隙赁。
- 組件生命周期大致分為三個(gè)階段,實(shí)例化階段梆暖,運(yùn)行階段伞访,銷毀階段。
組件生命周期
實(shí)例化階段
- constructor:
- 什么時(shí)候調(diào)用:在一開始實(shí)例化組件的時(shí)候調(diào)用
- 作用:初始化state.
- componentWillMount:
- 什么時(shí)候調(diào)用:即將加載組件的時(shí)候調(diào)用
- 作用:在render之前做事情
- render:
- 什么時(shí)候調(diào)用:渲染組件的時(shí)候調(diào)用
- 作用:通過這個(gè)方法
- componentDidMount:
- 什么時(shí)候調(diào)用:加載組件完成的時(shí)候調(diào)用
- 作用:在render之后做事情轰驳,發(fā)送請(qǐng)求
- 注意:
constructor厚掷,componentWillMount,componentDidMount
只會(huì)調(diào)用一次 - 運(yùn)行結(jié)果
運(yùn)行階段
-
componentWillReceiveProps:
- 什么時(shí)候調(diào)用:每次傳入Props级解,就會(huì)調(diào)用
- 作用:攔截props
-
shouldComponentUpdate:
- 什么時(shí)候調(diào)用:每次props,或者state改變冒黑,就會(huì)調(diào)用
- 作用:控制是否刷新界面
-
componentWillUpdate:
- 什么時(shí)候調(diào)用:組件即將更新調(diào)用
- 作用:在render更新前做事情
-
componentDidUpdate:
- 什么時(shí)候調(diào)用:組件更新完成調(diào)用
- 作用:在render更新后做事情
注意:絕對(duì)不要在
componentWillUpdate,componentDidUpdate
中調(diào)用this.setState
方法勤哗,否則將導(dǎo)致無限循環(huán)調(diào)用抡爹,在componentWillReceiveProps,shouldComponentUpdate
可以芒划。運(yùn)行效果
銷毀階段
- componentWillUnmount:
- 什么時(shí)候調(diào)用:組件即將銷毀的時(shí)候調(diào)用
- 作用:移除觀察者冬竟,清空數(shù)據(jù)
使用
class LifeCompoent extends Component {
constructor(props){
super(props);
self.state = {
age:0
}
console.log('constructor');
}
componentWillMount() {
console.log('componentWillMount');
}
componentDidMount() {
console.log('componentDidMount');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate');
return true;
}
componentWillReceiveProps() {
console.log('componentWillReceiveProps');
}
componentWillUpdate() {
console.log('componentWillUpdate');
this.setState({
age:1
});
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
componentWillUnmount() {
console.log('componentWillUpdate');
}
render(){
console.log('render');
return (
<View style={styles.lifeStyle} >
<Text onPress={()=>{
this.setState({
age:1
});
}}>修改state</Text>
</View>
);
}
}
export default class ReactDemo extends Component {
constructor(props){
super(props);
this.state = {
name:'xmg'
}
}
render() {
return (
<View style={{flex:1,marginBottom:50}}>
<LifeCompoent name={this.state.name} />
<Text onPress={()=>{
this.setState({
name : 'yz'
})
}}>修改props</Text>
</View>
);
}
}
const styles = StyleSheet.create({
lifeStyle:{
flex:1,
justifyContent:'center',
alignItems:'center'
}
});
AppRegistry.registerComponent('React', () => ReactDemo);