React Native 中 component 生命周期参考:https://blog.youkuaiyun.com/ElinaVampire/article/details/51813677
test1.js
import React, { Component } from 'react';
import {
View,
} from 'react-native';
import Test2 from "./Test2";
export default class Test1 extends Component{
constructor(props) {
super(props);
this.state ={
name:'1'
}
}
componentWillUnmount(){
console.log('test1 componentWillUnmount...');
}
componentDidMount(){
setTimeout(()=>{
console.log('update test1 state...');
this.setState({name:'2'});
},2000);
console.log('test1 componentDidMount...');
}
componentWillReceiveProps(){
console.log('test1 componentWillReceiveProps...');
}
shouldComponentUpdate(){
console.log('test1 shouldComponentUpdate...');
return true;
}
componentWillUpdate(){
console.log('test1 componentWillUpdate...');
}
componentDidUpdate(){
console.log('test1 componentDidUpdate...');
}
componentWillUnmount(){
console.log('test1 componentWillUnmount...');
}
componentWillMount(){
console.log('test1 componentWillMount...');
}
render() {
console.log('test1 render...');
return (
<View style={{flex:1}}>
<Test2 sex={'男'}></Test2>
</View>
);
}
};
test2.js
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class Test2 extends Component{
constructor(props) {
super(props);
}
componentWillUnmount(){
console.log('test2 componentWillUnmount...');
}
componentDidMount(){
console.log('test2 componentDidMount...');
}
componentWillReceiveProps(nextProps){
console.log(this.props);
console.log(nextProps);
console.log('test2 componentWillReceiveProps...');
}
shouldComponentUpdate(){
console.log('test2 shouldComponentUpdate...');
return true;
}
componentWillUpdate(){
console.log('test2 componentWillUpdate...');
}
componentDidUpdate(){
console.log('test2 componentDidUpdate...');
}
componentWillMount(){
console.log('test2 componentWillMount...');
}
render() {
console.log('test2 render...');
return (
<View style={{flex:1}}>
<Text>Test2</Text>
</View>
);
}
};
控制台打印情况:
test1 componentWillMount...
test1 render...
test2 componentWillMount...
test2 render...
test2 componentDidMount...
test1 componentDidMount...
update test1 state...
test1 shouldComponentUpdate...
test1 componentWillUpdate...
test1 render...
{sex: "男"}
{sex: "男"}
test2 componentWillReceiveProps...
test2 shouldComponentUpdate...
test2 componentWillUpdate...
test2 render...
test2 componentDidUpdate...
test1 componentDidUpdate...
父组件的state更新之后,父组件的shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate会执行;同时子组件的componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate也会执行,需要对业务逻辑进行控制的,可以在各个component中写相应的代码。