【发布时间】:2018-11-07 16:32:29
【问题描述】:
我通过下面的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;
}
}
【问题讨论】:
标签: javascript reactjs react-native