a dive in react lifecycle

Posted yadiblogs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了a dive in react lifecycle相关的知识,希望对你有一定的参考价值。

背景:我在react文档里找生命周期的图,居然没有,不敢相信我是在推特上找到的。。。

技术分享图片

正文

react v16.3 新生命周期:

  • static getDerivedStateFromProps
  • getSnapshotBeforeUpdata

1: getDerivedStateFromProps, 在render之前,返回一个obj更新state,或者null不更新state, 这个生命周期的使用场景是:state根据props变化。

 static getDerivedStateFromProps(nextProps: SearchProps, prevState: SearchState) {
    const { location } = nextProps
    const state = location.state
    if (state && (state.keyword !== prevState.keyword)) {
      const { keyword } = statereturn {
        pageState: 0,
        employee: {
          hit: 0,
          count: 0,
          data: [],
          currentOffset: 0
        },
        document: {
          hit: 0,
          count: 0,
          data: [],
          currentOffset: 0
        },
        keyword,
        needExact: false
      }
    }
    return null
  }

2: getSnapshotBeforeUpdata  触发时间:在实际dom挂载之前,虚拟dom构建之后。返回的任何数据或者null,都将作为componentDidUpdate()的参数。

 getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    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 we have a snapshot value, we‘ve just added new items.
    // Adjust scroll so these new items don‘t push the old ones out of view.
    // (snapshot here is the value returned from getSnapshotBeforeUpdate)
    if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }

建议用法总结请移步:https://juejin.im/post/5aca20c96fb9a028d700e1ce

这里拷贝一个我用到的一种情况:props更新时重新请求

// old
  componentWillReceiveProps(nextProps) {
    if (nextProps.id !== this.props.id) {
        this.setState({externalData: null});
      this._loadAsyncData(nextProps.id);
    }
  }

// new
  static getDerivedStateFromProps(nextProps, prevState) {
    // Store prevId in state so we can compare when props change.
    if (nextProps.id !== prevState.prevId) {
      return {
        externalData: null,
        prevId: nextProps.id,
      };
    }
    // No state update necessary
    return null;
  }
  componentDidUpdate(prevProps, prevState) {
    if (this.state.externalData === null) {
      this._loadAsyncData(this.props.id);
    }
  }

我的使用:

  componentDidUpdate(prevProps: SearchProps, prevState: SearchState) {
    const { keyword, needExact } = this.state
    if (keyword && (keyword !== prevState.keyword)) {  // 上一次的state和这一次的对比,如果需要,就进行fetch数据,并setstate。其中this.state就是getDerivedStateFromProps返回的 更新后的state
      if (needExact) {
        this._fetchExactData(this.state.keyword)
        this.setState({
          needExact: false
        })
      } else {
        Promise.all([this._fetchInitData(‘document‘), this._fetchInitData(‘employee‘)])
          .then(values => {
            let pageState = 0
            const { state } = this.props.location 
            if (state && state.type) {
              pageState = state.type
            } else if (!values[1] && values[0]) {
              pageState = 1
            }
            this.setState({
              pageState,
            })
          })
      }
    }
  }

最后,记录一个小知识点:

由于state变化,需要出发请求数据的,在componentDidUpdate中进行。

以上是关于a dive in react lifecycle的主要内容,如果未能解决你的问题,请参考以下文章

A Deep Dive into Rescalable State in Apache Flink

前端框架sourceCode dive

React.js Tutorial: React Component Lifecycle

React (Native) Rendering Lifecycle

The lifecycle of react

React 入门 -- 生命周期 LifeCycle