生命周期函数分类
分成三部分
- 组件创建阶段:一辈子只执行依次
- constructor
- componentWillMount
- render
- componentDidMount
- 组件运行阶段:按需,根据props属性或state状态的改变,有选择性的执行0到多次
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidupdate
- 组件销毁阶段:一辈子只执行一次
- componentWillUnmount
流程图
Ajax获取数据
如果想在组件的加载前就获取数据,应该在哪里执行Ajax
。
应该在
componentWillMount
和componentWillUpdate
中执行。
shouldComponentUpdate(nextProps,nextState)
- 判断组件是否应该更新
- 当父组件传给子组件Props时,子组件就会执行shouldComponentUpdate函数
- 根据父组件传给子组件的下一个props和下一个state决定子组件是否更新