组件的生命周期分为三个状态
- Mounting:已插入真实DOM
- Updating:正在被重新渲染
- Unmounting:已移出真实DOM
Mounting (装载)
-
getInitialState()在组件挂载之前调用一次,返回值将作为this.state的初始值. -
componentWillMount():服务器和客户端只调用一次,在初始化渲染之前调用. -
componentDidMount():在初始化渲染执行完成后立即调用一次.仅客户端调用,服务端不调用.
和iOS的UIViewController里的viewWillAppear和viewDidAppear方法类似
Updating (更新会多次调用)
-
componentWillReceiveProps(object nextProps)在组件接收到新的props的时候调用,在初始化时该方法不调用. -
shouldComponentUpdate(object nextProps ,object nextState)在接收新的props或state将要渲染之前调用.
- 该方法在初始化渲染的时候不会调用,在使用
forceUpdate方法的时候也不会.如果确定新的props和state不会导致组件更新,则此处应该 返回 false.
-
componentWillUpdate(object nextProps, object nextState):在接收到新的props或者state之前立刻调用.
- 在初始化渲染的时候该方法不会被调用.使用该方法做一些更新之前的准备工作.
- 不能在该方法中使用
this.setState().如果需要更新state来响应某个prop的改变,请使用componentWillReceiveProps
-
componentDidUpdate(object prevProps, object prevState): 在组件的更新已经同步到DOM中之后立刻被调用.
- 该方法不会在初始化渲染的时候调用。使用该方法可以在组件更新之后操作 DOM 元素。
Unmounting(移除)
-
componentWillUnmount在组件从 DOM 中移除的时候立刻被调用
- 在该方法中执行任何必要的清理,比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素.
export default class LifeCycleComponent extends Component{
constructor(props){ //完成组件的初始化
super(props);
console.log('----controuctor----');
}
componentWillMount(){
console.log('----componentWillMount ----');
}
componentDidMount(){
console.log('----componentDidMount----');
}
componentWillReceiveProps(props){
console.log('----componentWillReceiveProps----');
}
shouldComponentUpdate(nextProps,nextState){
console.log('----shoudComponentUpdate----');
return true;
}
componentWillUpdate(nextProps,nextState){
console.log('----componentWillUpdate----');
}
componentDidUpdate(nextProps,nextState){
console.log('----componentDidUpdate----');
}
componentWillUnmount(){
console.log('----componentWillUnmount----');
}
render(){
console.log('----render----');
return <Text style={{fontSize:20}}>hello.{this.props.name}</Text>
}
}

image.png
由运行结果可以知道先调用装载的componentWillMount和componentDidMount
修改state值
constructor(props){ //完成组件的初始化
super(props);
this.state={
count : 0,
}
console.log('----controuctor----');
}
render(){
console.log('----render----');
return <View>
<Text style={{fontSize:20}}
onPress={()=>{
this.setState({
count:this.state.count+1,
})
}}
>hello</Text>
<Text style={{fontSize:20}}>点击了{this.state.count}次</Text>
</View>
}
当点击hello时修改state会先触发shouldComponentUpdate然后在componentWillUpdate最后在componentDidUpdate
如下图打印结果

image.png
在App.js文件里修改来模拟移除组件
export default class App extends Component<Props> {
constructor(props){
super(props);
this.state={
remove:false,
}
}
render() {
var myView = this.state.remove?null:<LifeCycleComponent />;
var myText = this.state.remove?"添加myView":"移除myView";
return (
<View style={styles.container}>
<Text
style={{fontSize:20}}
onPress={()=>{
this.setState({
remove : !this.state.remove
})
}}>{myText}
</Text>
{myView}
</View>
);
}
}
点击移除时会触发componentWillUnmount

image.png