React的生命周期
挂载卸载过程
-
constructor()
初始化state或者进行方法绑定
在组件挂载之前会调用它的构造函数,它接受两个参数:props和context,当想在函数内部使用这两个参数时,需使用super()传入这两个参数。
注意:只要使用了constructor()就必须写super(),否则会报出this指向错误在react中,构造函数仅用于以下两种情况:
- 通常给this.state赋值对象来初始化内部的state
- 为事件处理函数绑定实例
在constructor()函数中不要调用setState()方法
-
static getDerivedStateFromProps(props,state)
从属性里面获取派生状态,初始化的时候及后续更新时都会执行,根据外部传入的属性从而更新自身状态
**注意:**这个钩子函数必须要有一个返回值,如果props传入的内容不需要影响到你的state,那么就需要返回一个null
static getDerivedStateFromProps(nextProps, prevState) { const {type} = nextProps; // 当传入的type发生变化的时候,更新state if (type !== prevState.type) { return { type, }; } // 否则,对于state不进行任何操作 return null; }
-
render()
render()
方法是 class 组件中唯一必须实现的方法。注意:
当组件的状态或者外部传入进来的属性发生改变的时候,组件的render函数会重新执行。 -
componentDidMount()
componentDidMount()会在组件挂载后立即调用.可以使用此钩子函数发送ajax异步请求操作
-
componentWillUnmount()
componentWillUnmount()会在组件卸载及销毁之前直接调用.在这个方法中执行必要的请求操作,比如可以将componentDidMount绑定的定时器及时的清掉
更新组件阶段
-
static getDerivedStateFromProps(props,state)
-
shouldComponentUpdate(nextProps,nextState)
通过这个方法可以询问组件是否进行更新操作,如果不写默认是返回true,代表这个组件要更新,就会走render()方法.
如果这个钩子函数返回false,就代表不让组件更新,就不会走render()方法
如果内部想要获取最新的属性或者状态,需要从参数里面获取
在react中可以通过这个钩子函数去提升react的性能
shouldComponentUpdate(nextprops,nextState){ // 之前的属性值与最新的属性值如果不一样的话,才会返回true if(this.props.flag !== nextprops.flag){ return true } return false }
补充:也可以通过PureComponent这个纯组件实现此功能
使用纯组件的话,组件内部不能再写shouldComponentUpdate这个钩子函数了
内部通过浅比较(进行值比较或者内部地址的比较),进行性能的优化
export default class index extends PureComponent
-
render()
-
getSnapshotBeforeUpdate(prevProps, prevState)
代替componentWillUpdate
getSnapshotBeforeUpdate 会在最终的 render 之前被调用,也就是说在 getSnapshotBeforeUpdate 中读取到的 DOM 元素状态是可以保证与 componentDidUpdate 中一致的.这个钩子的返回值将会作为参数传递给componentDidUpdate()
-
componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate()会在更新后被立即调用.首次渲染时不会执行这个方法.可以将每次更新都要进行的行动写在这个方法中,比如轮播图的实例化操作
如果getSnapshotBeforeUpdate有返回值的话,那么这个钩子函数第三个参数就可以获取到返回值了