using shouldComponentUpdate instead of getSnapshotBeforeUpdate
还没有人认领这个 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?
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
该 issue 提供了一个内联 TypeScript ScrollLock 组件,而没有指出 repository 文件或测试。首先查看 React 关于 shouldComponentUpdate、getSnapshotBeforeUpdate 和 componentDidUpdate 的生命周期文档;当针对这一滚动锁定场景的正确生命周期方案得到确定并记录后,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react, typescript
- 领域
- documentation, frontend
- Issue 类型
- 文档
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100