react生命周期

发布时间 2023-03-28 18:45:45作者: 这是啥!啥!啥

componentWillMount:16版本就废弃了,相当于Vue中created;

componentDidMount: 会在组件挂载后(插入DOM中)立即调用;相当于Vue中的onMounted;

componentDidUpdate(prevProps, prevState, snapshot):会在更新后会被立即调用,首次渲染不会执行;相当于Vue中的onUpdated;

componentWillUnmount():会在组件卸载和销毁之前调用:相当于Vue中的unmounted

不常用的生命周期方法

shouldComponentUpdate(nextProps, nextState): 判断react组件的输入是否受当前state || props更改影响,默认state每次发生改变组件都会重新渲染。主要是性能优化;

getDerivedStateFromProps(props, state):调用render方法前调用,初始化挂载及后续更新都会被调用,返回对象来更新state,返回null不更新任何内容;

getSnapshotBeforeUpdate(prevProps,prevState)最近一次渲染输入(提交DOM节点)前调用。组件发生改变之前从DOM捕获一些信息(滚动位置);返回值将作为参数传递给componentDidUpdate();

getDerivedStateFromError(err)会在后代组件抛出错误后调用,将错误作为参数,并返回一个值更新state;

componentDidCatch(error,info)在后代组件抛出错误后被调用;

挂在阶段:

  1.constructor初始化state对象或者给自定义方法绑定this

  2.getDerivedStateFromProps:接受到新的属性想去修改state,可以使用getDerivedStateFromProps

  3.render:返回需要渲染Dom,组件等;

  4.componentDidMount:组件装载之后调用,此时可以获取到DOM节点并操作,订阅放在这里;

更新阶段:

  1.getDerivedStateFromProps:更新个挂在阶段都可能会调用

  2.shouldComponentUpdate(nextProps, nextState)表示新的属性和变化之后的state,返回一个布尔值,true表示会触发重新渲染,false表示不会触发重新渲染,默认返回true,优化react程序性能;

  3.render

  4,getSnapshotBeforeUpdate(prevProps.prevState)这个函数有一个返回值作为第三个参数传给componentDidUpdate,

  5.componentDidUpdate(prevProps,prevState,snapshot)

卸载阶段:

  1.componentWillUnmount:当组件被卸载销毁调用