react生命周期

200 阅读1分钟

被废弃的生命周期

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

新的生命周期

  • 挂载
    1. constructor(构造函数只会执行一次)
    2. static getDerivedStateFromProps(nextProps, prevState)
    3. render
    4. componentDidMount
  • 更新(re-render)
    1. static getDerivedStateFromProps(nextProps, prevState)
    2. shouldComponentUpdate(nextProps, nextState)
    3. render
    4. getSnapshotBeforeUpdate(prevProps, prevState)
    5. componentDidUpdate(prevProps, prevState)
  • 销毁
    1. componentWillUnmount

错误捕获

  1. static getDerivedStateFromError(在errorBoundary中使用)
  2. componentDidCatch

getDerivedStateFromProps

这个生命周期函数是为了替代componentWillReceiveProps,该函数会在组件实例化以及接收新props后调用(state变化也会调用,re-render都会调用)。它可以返回一个对象来更新state,或者返回null来表示新的props不需要任何state更新。函数会在每一次re-render之前调用,即使props没有改变,setState导致state改变,该函数依然会被调用,getDerivedStateFromProps是一个静态函数,也就是这个函数不能通过this访问到class的属性,不推荐直接访问属性。而是应该通过参数提供的nextProps以及prevState来进行判断,根据新传入的props来映射到state。如果props传入的内容不需要影响到你的state,那么就需要返回一个null,这个返回值是必须的。

static getDerivedStateFromProps(nextProps, prevState) {
  const { type } = nextProps;
  // 当传入的type发生变化的时候,更新state
  if (type !== prevState.type) {
    return {
      type,
    };
  }
  // 否则,对于state不进行任何操作
  return null;
}

getSnapshotBeforeUpdate

此生命周期的返回值将作为第三个参数传递给componentDidUpdate生命周期。

class ScrollingList extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <div ref={this.listRef}>
        {/* ...contents... */}
      </div>
    );
  }
}