[中级]ReactClass组件:看这一篇就够了

594 阅读6分钟

概览

我们编写的大部分 React 的组件都为class组件,掌握class组件的原理和应用能帮助我们写出更好的代码,本文主要会从生命周期、state状态这两个方面来介绍ReactClass组件,阅读本文能让你快速掌握ReactClass组件的要点。

生命周期

我会先向大家讲解react16.3以后的生命周期,然后解释下部分老旧的生命周期钩子被废弃/不推荐使用的原因。

执行顺序

image.png 以上是react官方给出的生命周期图谱,大致分为3个阶段,Mounting、Updating、Unmounting,下面是每个阶段的执行顺序。

Mounting

Mounting阶段的执行顺序依次为:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Updating

Updating阶段的执行顺序依次为:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

Unmounting

Unmounting阶段只会调用一个函数:

  • componentWillUnmount()

Error

除了以上3个阶段,React在错误发生时还提供了两个钩子用来做一些错误降级/上报处理:

  • static getDerivedStateFromError()
  • componentDidCatch() 以上两个方法的区别在于,static getDerivedStateFromError()方法用于降级,而componentDidCatch()用于一些错误上报。

钩子详解

下面会详细解释上面提到的每一个钩子

constructor(props)

constructor(props)为class组件的构造函数,一般有两个作用:

  • 给state对象初始化赋值
  • 处理方法,比如防抖、节流、bind等
 constructor(props) {
    super(props)
    this.state = {id: 1}
    this.onSelectUser = throttle(this.onSelectUser, 500)
  }

以上代码首先给state赋了初始值,然后将onSelectUser方法用节流函数处理后得到了一个新方法。

static getDerivedStateFromProps(props, state)

该函数有两个要点:

  • 每次render前都会调用该方法,也就是说无论是初始化阶段还是更新阶段都会调用static getDerivedStateFromProps(props, state)。
  • 该函数的作用很简单:return一个对象来更新state,如果return null则不更新任何内容。
static getDerivedStateFromProps(props, state) {
    if (props.id !== state.id) {
      return {
        id: props.id
      }
    }
    if (typeof props.expandedkey !== 'undefined') {
      return {
        expandedkey: props.expandedkey
      }
    }
    return null
  }

以上代码为一个示例,需要注意的是,该方法无法访问组件实例,所以你仅仅能根据props和state的值经过一些条件比较,最后return一个对象更新state的值。

shouldComponentUpdate(nextProps, nextState)

该函数的唯一作用为return一个布尔值来决定是否重新渲染组件,true为更新,false为不更新

shouldComponentUpdate(nextProps, nextState) {
    if (this.props.text !== nextProps.text) {
      return true
    }
    if (this.state.weight !== nextState.weight) {
      return true
    }
    return false
  }

以上示例中可以看到,在shouldComponentUpdate方法中,我们能获得nextProps、nextState从而与this.props、this.state进行比较,最后决定组件的更新与否。

render()

该函数最为常用,我们需要知道render函数究竟怎么渲染为dom节点。 render函数会返回以下类型之一:

  • React元素:<div/>会被渲染为dom节点,<MyComponent/>会被渲染为自定义组件,这两种都为React元素,react根据第一个字母的大小写来决定时是dom节点还是自定义组件。
  • 数组或 fragments
  • Portals
  • 字符串或数值类型
  • 布尔类型或 null 在render函数中,react会先判断元素的类型,然后根据不行的类型执行不同的解析方法。

componentDidMount()

一般人对该方法都比较熟悉,componentDidMount的调用时机在组件第一次render之后,一般可以在此方法中使用ajax请求获取数据后使用setState再次更新状态。

componentDidMount() {
    this.props.getCode({
      id: 'clue'
    }).then((res) => {
      if(res.code){
       setState({
         code: res.code
       })
      }
    }).catch(err){
      console.log(err)  
    }
  }

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate会在更新阶段的render后被调用

componentDidUpdate(prevProps) {
    if (prevProps.refresh !== this.props.refresh) {
      this.init()
      this.ajax()
    }
  }

如上示例,一般在componentDidUpdate中会对prevProps、prevState、props、state进行一些比较,然后执行ajax请求或其他函数。

getSnapshotBeforeUpdate(prevProps, prevState)

  • 仅在更新阶段的render函数之后被调用
  • 返回一个值,该值会作为componentDidUpdate方法的第三个参数
getSnapshotBeforeUpdate(prevProps, prevState) {
  return this.testNode.scrollHeight
}
componentDidUpdate(prevProps, prevState, snapshot) {
  console.log(snapshot)
}
render(){
  return (
    <div ref = { node => (  this.testNode = node)}> </div>
  )
}

如上示例,在getSnapshotBeforeUpdate方法中适合获取dom的一些位置属性然后return,并在componentDidUpdate方法中作为第三个参数传入。

componentWillUnmount()

componentWillUnmount() 会在组件卸载及销毁之前直接调用,一般在此方法中清除一些内存,比如清除定时器、中断网络请求等。

componentWillUnmount(){
    // 清除定时器
    this.timer = null
}

componentDidCatch(error, info)

该方法的两个参数分别为:

  • error:抛出的错误
  • info:有关组件引发错误的栈信息
componentDidCatch(error, info) {
    log(info.componentStack);
  }

如上示例,一般在componentDidCatch方法中上报一些错误至监控平台,有时也会在最外层React组件的componentDidCatch方法中对所有error错误进行捕获。

static getDerivedStateFromError(error)

该方法会在后代组件抛出错误后被调用,在错误发生时,会返回一个对象来更新state,以达到降级的目的。以上两个方法的区别在于,getDerivedStateFromError方法用于降级,而componentDidCatch用于一些错误上报。

被弃用的钩子

image.png 以下生命周期都是要被废除掉的,暂时可以不用关注。

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate 官方给出的解释为:这些生命周期方法经常被误解和滥用。
    以componentWillUpdate为例:在异步模式下使用 componentWillUpdate 都是不安全的,想象一下在componentWillUpdate中调用外部回调,改变外部状态以后又可能触发props改变,从而又会调用componentWillUpdate,从而陷入死循环。而在componentDidUpdate方法能保证每次更新只调用一次,使用上更加安全。

组件状态

梳理生命周期能帮助我们熟练书写React代码,而理解组件状态如何更新,则帮助我们在应对疑难问题时更加轻松。
在React中,我们使用setState(updater, [callback])更新组件状态,因为setState并不立刻执行,所以在setState之后我们无法立刻获得组件的最新state。

setState({id:1}, () => {
   console.log(this.state.id)
})

如上代码所示,React提供了一种方式:即在setState的回调函数中获得最新的state(在componentDidUpdate中也能获取到最新state)。

既然如此,setState为什么不做成同步呢,做成异步很重要的一个原因是:性能优化,合并多个setState,避免多次渲染。

React事件中的setState会被存放于一个pending队列中,当同步代码都执行完后,才会批量更新state。由于setState的异步执行是基于React事件,所以像原生js事件以及setTimeout定时器中的setState方法就不会走异步逻辑,在这些情况下,我们可以同步获取最新state。

this.state = {
    id: 1
}
componentDidMount() {
    this.setState({id: this.state.id + 1 });
    console.log(this.state.id);

    this.setState({id: this.state.id + 1 });
    console.log(this.state.id);

    setTimeout(() => {
      console.log(this.state.id);
      this.setState({id: this.state.id + 1 });
      console.log(this.state.id);
      
    }, 0);
  }

以上代码的执行结果为0 0 1 2,我们简要分析一下:
因为setState为异步,一开始的两次setState都进入了pending队列,所以打印出来都是0,setTimeout为宏任务,setTimeout中的state是setState合并执行后的结果,此时id为1;而为什么在最后一次setState后打印出了最新的id(2)呢?这是因为setState的异步依赖于React事件,此时setState在原生js定时器中执行,无法实现异步setState,所以能同步获取到最新的state。

除了setState以外,React还提供了一个forceUpdate()函数来让组件强制渲染,但是我们在编写代码时应该尽量不使用该方法。

总结

  • 在日常开发中,可以经常回顾以上Mounting、Updating、Unmounting的生命周期。
  • 遇到旧代码中的被废弃的生命周期钩子时可查阅相关使用,并尝试将其升级。
  • 使用setState时需要注意,在原生js事件、setTimeOut等操作中的setState是同步更新状态的。