喜迎
春节

React-生命周期详解


前言: 只有class组件才有生命周期,function式的组件见没有生命周期(生命周期其实就是里面的一些回调函数)

生命周期阶段

  1. 挂载阶段
  • constructor(props)(在这里初始化state,这个只会执行一次),如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
    通常,在 React 中,构造函数仅用于以下两种情况:
    通过给 this.state 赋值对象来初始化内部 state,
    为事件处理函数绑定实例
  • static getDerivedStateFromProps()
  • render(只负责渲染,这几个带will的都在render之前执行),如果 shouldComponentUpdate() 返回 false,则不会调用 render()和componentDidMount。
  • componentDidMount(在这个获取到真实的DOM)
    -注-:Ajax请求在componentDidMount()里做
    这个即将不用:
    UNSAFE_componentWillMount(即将挂载)会和static getDerivedStateFromProps()互斥
  1. 更新(当组件的props或者state发生变化时触发)
    static getDerivedStateFromProps(新版本加入,这里面没有this,在实例创建前就已经存在)
    shouldComponentUpdate(很重要,组件是否需要更新)
    render()
    getSnapshotBeforeUpdate()
    componentDidMount()
    这两个即将不用:
    UNSAFE_componentWillUpdate()
    UNSAFE_componentWillReceiveProps(nextProps,nextState)

  2. 卸载

  • componentWillUnmount(在这里会清除定时器等)
  1. 错误处理
  • static getDerivedStateFromError()
  • componentDidcatch()
    生命周期图谱
  1. shouldComponentUpdate()可以在这里做性能优化
  • 第一个做法,使用shouldComponentUpdate
shouldComponentUpdate (nextProps,nextState) {
    return nextProps.isCompleted !== this.props.isCompleted
  }
  • 第二个做法,利用PurComponent(纯组件),是自动在shouldComponentUpdate里做了一次浅比较,所以有时候还会再做一次shouldComponentUpdate
    首先需要import引入,然后在原来写component的地方用PurComponent代替

  • 如果想要把状态切换做成state方式:
// TodoItem.js
export default class TodoItem extends Component {
  constructor () {
    super()
    this.state = {
      completedText: ''
    }
  }
  shouldComponentUpdate (nextProps,nextState) {
    return nextProps.isCompleted !== this.props.isCompleted
  }
  static getDerivedStateFromProps (props) {
    return {
      completedText: props.isCompleted ? '完成' : '未完成'
    }
  }

文章作者: NekoDeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 NekoDeng !
评 论
 上一篇
Vue-router
Vue-router
前言:vue-router是什么?为什么我们不像原来一样直接用 a 标签编写链接?如何使用?常见路由操作有哪些? Vue Router是什么Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构
2020-09-30
下一篇 
Git踩坑-git报错bad signature和index file corrupt和error:spawn failed的处理方法
Git踩坑-git报错bad signature和index file corrupt和error:spawn failed的处理方法
前言: 今天在部署写好的博客文章时,出现了git报错bad signature和index file corrupt和error:spawn failed,网上找了一堆解决办法,都没行,最后利用了巧妙地方法解决了。 问题描述git报错ba
2020-09-28
  目录