react16生命周期方法

全部生命周期方法:

  • constructor
  • getDerivedStateFromProps new
  • render
  • componentDidMount
  • getDerivedStateFromProps new
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate new
  • componentDidUpdate
  • componentWillUnmount
  • getDerivedStateFromError new
  • componentDidCatch new

constructor (props)

constructor通常用来初始化state,声明ref,绑定方法react

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
    };
    this.ref = React.createRef();
    this.handleClick = this.handleClick.bind(this)
  }
}

new static getDerivedStateFromProps (props, state)

getDerivedStateFromProps会根据props的值返回一个对象,该返回值将成为this.state的新值。
该方法会在两个时间触发:一是首次render以前,另外一次是每次组件更新时shouldComponentUpdate以前。
这里先讲首次render以前触发,这个时候使用它通常是用来根据props的值初始化state,固然能够直接在constructor里初始化state。dom

static getDerivedStateFromProps(props, state) {
  return { count: props.count };
}

render

render主要做用就是返回一段JSX,表示想要渲染的内容。若是返回值是null或false则不会渲染任何内容。性能

render () {
  return (
    <div>
      <h1>title</h1>
      <p>description</p>
    </div>
  )
}

componentDidMount

通常在componentDidMount里处理组件装载好以后才能够进行的操做,好比绑定事件、发送数据请求、或者进行一些dom相关的操做fetch

componentDidMount () => {
  window.addEventListener('scroll', this.handleScroll)
  this.timeout = setTimeout(() => {
    console.log(new Date())
  }, 500)
}

new static getDerivedStateFromProps (props, state)

当props改变或state改变时,组件从新渲染就会再次进入该声明周期方法中。这个时候能够根据props的值来更新state,返回新的state值,返回null则表示不更新。
在旧的生命周期方法componentWillReceiveProps中,咱们常常会比较this.props和nextProps来决定是否更新state或作别的事情,好比:this

componentWillReceiveProps (nextProps) {
 if (this.props.count !== nextProps.count) {
    this.setState({ count: nextProps.count })
    this.fetchData()
 }
}

getDerivedStateFromProps是静态方法,没法取到当前类组件的实例,因此没有办法进行this.prop和nextProps的比较,若是要比较的话只能进行props和当前state的比较,以下:code

if (props.count !== state.count) {
  return {
    ...
    count: props.count,
  };
  // 不更新state
  return null
}

除了不能比较this.prop和nextProps外,也不能在这个方法里调用当前实例的其余方法,好比this.fetchData,想调用的话得在componentDidUpdate里调用,这里在componentDidUpdate里会讲到。component

shouldComponentUpdate (nextProps, nextState)

当props或state的改变而使得组件须要从新渲染时,就会进入这个生命周期方法,它在render前触发。这个方法返回一个布尔值,用来表示组件是否须要从新渲染,默认值是true,表示老是从新渲染。咱们能够在这里加一些判断逻辑,只有当一些咱们真正关心的数据改变时咱们才从新渲染,好比:对象

shouldComponentUpdate(nextProps, nextState) {
  // 只有count改变页面才更新
  return nextState.count !== this.state.count;
}

shouldComponentUpdate经过避免没必要要的渲染来提高组件性能。不过使用很差的话会使得组件该渲染的时候不渲染,因此要谨慎使用。blog

new getSnapshotBeforeUpdate (prevProps, prevState)

这个方法会在组件更新时,render方法以后,可是dom尚未真正发生更新前执行。咱们能够根据更新前的props和state返回一个值,这个值将会做为下一个生命周期方法componentDidUpdate的第三个参数传入。能够用来与componentDidUpdate协做完成一些事情生命周期

getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevState.blocks.length < this.state.blocks.length) {
      const grid = this.grid.current;
      const isAtBottomOfGrid =
        window.innerHeight + window.pageYOffset === grid.scrollHeight;
      return { isAtBottomOfGrid };
    }
    return null;
  }

componentDidUpdate (prevProps, prevState, snapshot)

该生命周期方法会在组件渲染更新完成后执行,通常在这里作的事情是:根据props的改变作一些操做好比请求数据,根据snapshot的值作一些操做,或者是作一些dom操做等等。

一、根据props、state的改变作一些处理
在旧的生命周期方法componentWillReceiveProps中,常常会比较this.props和nextProps,来进行其余操做好比请求数据,或调用this.someFunc等,在新的生命周期方法中这部分操做能够在componentDidUpdate中完成。

componentDidUpdate (prevProps, prevState, snapshot) {
 if (this.props.count !== prevProps.count) {
    this.fetchData()
 }
}

二、根据第三个参数snapshot作一些处理
好比如下例子就是根据上面getSnapshotBeforeUpdate里返回的isAtBottomOfGrid来判断当前页面的滚动条是否是在底部,若是是的话,更新后还须要手动将滚动条滚到底部。

componentDidUpdate(prevProps, prevState, snapshot) {
  if (snapshot.isAtBottomOfGrid) {
    window.scrollTo({
      top: this.grid.current.scrollHeight,
      behavior: 'smooth',
    });
  }
}

componentWillUnmount

这个方法与componentDidMount是相对应的,在componentDidMount中绑定的事件、建立的定时器均可以在这个方法里清除

componentWillUnmount () => {
  window.removeEventListener('scroll', this.handleScroll}
  clearTimeout(this.timeout)
}

new static getDerivedStateFromError(error)

这个方法用来获取子组件抛出的错误,根据错误信息返回一个对象,为新的state的值。只能获取到子组件生命周期方法中抛出的错误,像this.handleClick里抛出的错误,不会触发该方法。这个方法只能用来返回错误,若是想打印错误或作其余处理,须要在componentDidCatch里写。

static getDerivedStateFromError(error) {
  return { hasError: true };
}

new componentDidCatch(error, info)

当子组件中抛出错误后,componentDidCatch就会触发,能够在这个方法里捕获错误、打印错误信息或上报错误信息等操做

componentDidCatch(error, info) {
  console.log(error, info);
}

参考:React 16 Lifecycle Methods: How and When to Use Them

相关文章
相关标签/搜索