最近在写一个主子组件嵌套关系复杂的项目,这就需要弄明白复杂单页面应用中主子以及祖先组件的生命周期函数的执行顺序,来进行数据请求与销毁。
以下是测试代码
class Child extends React.Component {
constructor(props, ...rest) {
super(props, ...rest);
console.log(this.props.name + " constructor");
}
componentWillMount(...args) {
console.log(this.props.name + " componentWillMount");
}
componentDidMount(...args) {
console.log(this.props.name + " componentDidMount");
}
render() {
console.log(this.props.name + " render");
return <div>Hi from {this.props.name}!</div>;
}
}
class Parent extends React.Component {
constructor(...args) {
super(...args);
console.log("Parent constructor");
}
componentWillMount(...args) {
console.log("Parent componentWillMount");
}
componentDidMount(...args) {
console.log("Parent componentDidMount");
}
render() {
console.log("Parent render start");
const result =
<div>
<Child name="Child1" />
<Child name="Child2" />
</div>;
console.log("Parent render end");
return result;
}
}
Parent constructor
Parent componentWillMount
Parent render start
Parent render end
Child1 constructor
Child1 componentWillMount
Child1 render
Child2 constructor
Child2 componentWillMount
Child2 render
Child1 componentDidMount
Child2 componentDidMount
Parent componentDidMount