只执行一次: constructor、componentWillMount、componentDidMount
执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate
有条件的执行:componentWillUnmount(页面离开,组件销毁时)
父子组件生命周期执行顺序
// 父组件
export default class ParentCp extends Component {
constructor(props) {
super(props);
this.state = {
flag: true,
}
console.log("父组件构造函数")
}
UNSAFE_componentWillMount(){
console.log("父组件WillMount")
}
componentDidMount() {
console.log("父组件Mount")
}
UNSAFE_componentWillUpdate(){
console.log("父组件WillUpdate")
}
UNSAFE_componentWillReceiveProps(){
console.log("父组件WillReceiveProps")
}
shouldComponentUpdate(){
console.log("父组件shouldComponentUpdate")
return true
}
componentDidUpdate() {
console.log("父组件Update")
}
componentWillUnmount() {
console.log("父组件WillUnmount")
}
clickHandler = () => {
const {flag}=this.state
this.setState({
flag: !flag
})
}
render() {
const {flag}=this.state
console.log("父组件render")
return (
<div>
<Home flag={flag}></Home>
<About flag={flag}></About>
<div onClick={this.clickHandler}>切换</div>
</div>
);
}
}
// ...子组件同上
组件挂载过程
- constructor
- componentWillMount
- render
- componentDidMount
2.组件更新过程
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
组件卸载
- componentWillUnmount