生命周期函数分类

分成三部分

  1. 组件创建阶段:一辈子只执行依次
    1. constructor
    2. componentWillMount
    3. render
    4. componentDidMount
  2. 组件运行阶段:按需,根据props属性或state状态的改变,有选择性的执行0到多次
    1. componentWillReceiveProps
    2. shouldComponentUpdate
    3. componentWillUpdate
    4. render
    5. componentDidupdate
  3. 组件销毁阶段:一辈子只执行一次
    1. componentWillUnmount

流程图

image-20200802151354474

Ajax获取数据

如果想在组件的加载前就获取数据,应该在哪里执行Ajax

应该在componentWillMountcomponentWillUpdate中执行。

shouldComponentUpdate(nextProps,nextState)

  • 判断组件是否应该更新
  • 当父组件传给子组件Props时,子组件就会执行shouldComponentUpdate函数
  • 根据父组件传给子组件的下一个props和下一个state决定子组件是否更新

image-20200802151440561