reactjs / reactjs/react.dev

using shouldComponentUpdate instead of getSnapshotBeforeUpdate

オープン
#1,222 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

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?

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

この issue では、リポジトリのファイルやテストを指定する代わりに、インラインの TypeScript ScrollLock コンポーネントが示されています。まず、shouldComponentUpdate、getSnapshotBeforeUpdate、componentDidUpdate に関する React のライフサイクルドキュメントを確認してください。このスクロールロックのケースに対する正しいライフサイクルアプローチを確立し、文書化できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react, typescript
領域
documentation, frontend
issue の種類
ドキュメント
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。