react16生命周期方法

所有生命周期方法:

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

constructor (props)

constructor一般用来初始化state,声明ref,绑定方法

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。

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相关的操作

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或做别的事情,比如:

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

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

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

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

shouldComponentUpdate (nextProps, nextState)

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

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

shouldComponentUpdate通过避免不必要的渲染来提升组件性能。不过使用不好的话会使得组件该渲染的时候不渲染,所以要谨慎使用。

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操作等等。

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

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

2、根据第三个参数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

    原文作者:八神光
    原文地址: https://segmentfault.com/a/1190000017900649
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞