reactjs / reactjs/react.dev

using shouldComponentUpdate instead of getSnapshotBeforeUpdate

未关闭
#1,222 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
JavaScript
星标
11.8k
派生
7.9k
平均合并
1 天 11 小时
30 天内合并 PR
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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 提供了一个内联 TypeScript ScrollLock 组件,而没有指出 repository 文件或测试。首先查看 React 关于 shouldComponentUpdate、getSnapshotBeforeUpdate 和 componentDidUpdate 的生命周期文档;当针对这一滚动锁定场景的正确生命周期方案得到确定并记录后,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, react, typescript
领域
documentation, frontend
Issue 类型
文档
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。