react生命周期入门

什么是生命周期

生命周期函数(钩子函数)通俗的说就是在某一时刻会被自动调用执行的函数。

React的生命周期函数


react生命周期入门


componentWillMount

在渲染前调用,在客户端也在服务端。

React 16.3+版本中 componentWillMount 被重命名为
UNSAFE_componentWillUpdate()

ps: 不建议在componentWillMount 中做 AJAX 调用,代码里看到只有调用一次,但是实际上可能调用 N 多次,这明显不合适。相反,若把 AJAX 放在componentDidMount,因为 componentDidMount 在第二阶段,所以绝对不会多次重复调用,这才是 AJAX 合适的位置。


componentDidMount

在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()

来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval 或者发送AJAX请求等操作(防止异步操作阻塞UI)。

使用场景

  • 该方法中可以发起异步请求,可以执行setState
  • 该方法可以使用refs获取真实dom元素,进行dom相关操作
react生命周期入门


componentWillReceiveProps

在组件接收到一个新的 prop (更新后)时被调用。(首次并不会触发函数)。

使用场景:

  • 在接受父组件改变后的props需要重新渲染组件时用到的比较多
  • 接受一个参数nextProps
  • 通过对比nextProps和this.props,将nextProps的state为当前组件的state,从而重新渲染组件
 componentWillReceiveProps (nextProps) {
    nextProps.openNotice !== this.props.openNotice&&this.setState({
        openNotice:nextProps.openNotice
    }, () => {
        //将state更新为nextProps,在setState的第二个参数(回调)可以打印出新的state
      console.log(this.state.openNotice:nextProps)
  })
}

PS: React 16.3+版本中 componentWillReceiveProps被重命名
UNSAFE_componentWillReceiveProps()


shouldComponentUpdate

判断组件是否应该重新渲染,默认是true, 返回false时不会重写render

  • nextProps: 表示下一个props。
  • nextState: 表示下一个state的值。
  • shouldComponentUpdate(nextProps, nextState)

    用途:

  • 主要用于性能优化(部分更新)
  • 唯一用于控制组件重新渲染的生命周期,由于在react中,setState以后,state发生变化,组件会进入重新渲染的流程,在这里return false可以阻止组件的更新
  • 因为react父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断
  • eg:

    shouldComponentUpdate(nextProps, nextState) {
      return nextState.someData !== this.state.someData
    


    componentWillUpdate

    在组件接收到新的 props 或者 state 但还没有 render 时被调用。在初始化时不会被调用。

    PS:

    1. React 16.3+版本中 componentWillUpdate 被重命名 UNSAFE_componentWillUpdate()
    2. 不能在该函数中通过 this.setstate 再次改变 state,否则会造成无限循环。


    ComponentDidUpdate

    ComponentDidUpdate(nextProps, nextState)

  • nextProps: 表示下一个props。
  • nextState: 表示下一个state的值。
  • 使用场景:通过比较prevProps或prevState 与 this.props或this.state,进行业务处理,发送网络请求

    注意:在处理业务或发送网络请求时,一定要做条件比较,否则容易造成死循环


    componentWillUnmount

    在组件从 DOM 中移除之前立刻被调用。

    使用场景:清理无效

    timer、取消未完成的网络请求


    分享到:


    相關文章: