zoukankan      html  css  js  c++  java
  • 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中进行。

  • 相关阅读:
    linux常用命令
    linux下redis配置
    Git使用命令
    linux学习笔记
    NOPI读取Excel2003、Excel2007或更高级的兼容性问题
    netcore开发常用命令
    netcore3.0 dotnet ef执行报错
    vscode配置nuget常见问题
    PDMReader结合PowerDesigner导出word格式数据字典
    微信网页授权开发遇到问题
  • 原文地址:https://www.cnblogs.com/yadiblogs/p/9942960.html
Copyright © 2011-2022 走看看