reactjs / reactjs/react.dev

using shouldComponentUpdate instead of getSnapshotBeforeUpdate

Đang mở
#1,222 4 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Ngôn ngữ chính
JavaScript
Star
11.8k
Fork
7.9k
Merge trung bình
1 ngày 11 giờ
Pull request đã merge (30 ngày)
11

Mô tả

Hi, I'm struggling a little with the new lifecycles. I have this component which passes down a style which will lock the scrollbar on the window without shifting content when applied on my root App element.

interface ScrollLockProps {
  locked: boolean,
  children: (style?: CSSProperties) => React.ReactNode
}

export class ScrollLock extends React.Component<ScrollLockProps> {
  private scrollY = 0

  public shouldComponentUpdate() {
    if (!this.props.locked) {
      this.scrollY = window.scrollY
    }

    return true
  }

  public componentDidUpdate() {
    if (!this.props.locked) {
      window.scrollTo(0, this.scrollY)
    }
  }

  public render() {
    const { locked, children } = this.props

    const style: CSSProperties | undefined = locked ? {
      position: "fixed",
      left: "0px",
      right: "0px",
      top: `-${this.scrollY}px`,
    } : undefined

    return children(style)
  }
}

The problem is I have to use shouldComponentUpdate to retrieve the scroll position, and this feels wrong to me as this lifecycle surely should only return a boolean and not have any side effects?

I can't use getSnapshotBeforeUpdate because render is called before it, which means the resulting style will be incorrect.

And of course I cannot use componentWillReceiveProps because it is deprecated.
What is the correct way to go about this?

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Issue cung cấp một component ScrollLock TypeScript inline thay vì nêu tên các tệp hoặc bài kiểm thử trong repository. Hãy bắt đầu bằng cách xem lại tài liệu về vòng đời của React cho shouldComponentUpdate, getSnapshotBeforeUpdate và componentDidUpdate; công việc được xem là hoàn tất khi cách tiếp cận vòng đời đúng cho trường hợp khóa cuộn này được xác lập và ghi lại.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
javascript, react, typescript
Lĩnh vực
documentation, frontend
Loại issue
Tài liệu
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Cần làm rõ
Mức phù hợp với người mới
25/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.