CPPAlien / JS-QA

前端知识问答
0 stars 0 forks source link

getDerivedStateFromProps 和 getSnapshotBeforeUpdate 用法 #16

Open CPPAlien opened 5 years ago

CPPAlien commented 5 years ago

getDerivedStateFromProps: static 类型,在 component 每次 render 之前都会被执行,唯一存在的目的是在刷新前,允许组件根据 props 的变化而更新内部的 state。功能上有些像 componentWillReceiveProps,只是性能更好,为后续异步渲染机制做铺垫。不过也容易出 bug,建议少用。

getSnapshotBeforeUpdate: 在渲染内容被提交到 dom 前被调用,允许你获得 DOM 的一些信息。return 的数据可以在 componentDidUpdate 中获得。

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

  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;
    }
  }

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