react生命周期

43 阅读1分钟

只执行一次: 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>
    );
  }
}
// ...子组件同上
组件挂载过程
  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount

image.png

2.组件更新过程
  1. componentWillReceiveProps
  2. shouldComponentUpdate
  3. componentWillUpdate
  4. render
  5. componentDidUpdate

image.png

组件卸载
  1. componentWillUnmount

image.png