gpt4 book ai didi

javascript - React 中的 getSnapshotBeforeUpdate() 是什么?

转载 作者:行者123 更新时间:2023-12-03 13:28:03 24 4
gpt4 key购买 nike

我浏览了下面的React官方网站来了解新的生命周期方法getSnapshotBeforeUpdate

但我不明白这种方法的优点以及我们到底什么时候应该使用。

下面是文档中的示例,它区分了两种方法。

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

最佳答案

您引用的示例上面的两段解释了这样做的必要性:

In the above example, componentWillUpdate is used to read the DOM property. However with async rendering, there may be delays between “render” phase lifecycles (like componentWillUpdate and render) and “commit” phase lifecycles (like componentDidUpdate). If the user does something like resize the window during this time, the scrollHeight value read from componentWillUpdate will be stale.

The solution to this problem is to use the new “commit” phase lifecycle, getSnapshotBeforeUpdate. This method gets called immediately before mutations are made (e.g. before the DOM is updated). It can return a value for React to pass as a parameter to componentDidUpdate, which gets called immediately after mutations.

换句话来说:React 16.6 引入了一个名为 "Suspense" 的新功能。此功能支持异步渲染 - 可以延迟 React 组件子树的渲染(例如等待网络资源加载)。它也被 React 内部使用到 favor important DOM updates over others提高感知渲染性能。正如人们所期望的那样,这可能会导致 react 端虚拟 DOM 渲染(触发 componentWillUpdaterender() ,但可能包含一些必须等待的异步组件子树)和对 DOM 的实际反射之间存在大量延迟(触发 componentDidUpdate )。在 Suspense 之前的旧版 React 中,这些生命周期钩子(Hook)的调用总是几乎没有延迟,因为渲染是完全同步的,这证明了在 componentWillUpdate 中收集 DOM 信息的模式是合理的。并在 componentDidUpdate 中使用它,但情况已不再如此。

关于javascript - React 中的 getSnapshotBeforeUpdate() 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com