reactnative中父子元件中component執行順序
阿新 • • 發佈:2018-12-14
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中寫相應的程式碼。