恢复反应项目中的滚动位置(钩子)
我搜索了一些有关我的问题的答案,但发现了一个相关的答案。不幸的是,它甚至在类组件上,所以我想在导航回功能组件后恢复滚动位置。在这里我将分享 Stackblitz 上的源代码链接
I have searched a few answers regarding my issue but found one relevant. Unfortunately, it is even on the class component, so I want to restore the scroll position after navigating back on the functional component. Here I will share the source code link on Stackblitz
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有几个问题。
第一:
你看,
useState
中的 setter 没有this.setState()
那样有第二个参数。但是,您能问一下,为什么您的handleScrollPosition
会被调用吗?(因为您可以看到它在调试器中被调用)。原因是您已将其编写为handleScrollPosition()
,因此会立即调用它。为了证明我的观点,如果您将其更改为正确的“传递回调”形式:正如您在基于类的版本中已经拥有的那样,您将看到它从未被调用。同样,
即使显然
[].map()
不处理第 6 个参数,也会调用handleScrollPosition()
。那么你应该做什么?首先,让我们将滚动恢复移动到单独的
useEffect
中:显然它效果不佳,因为它将在获取数据之前立即调用。因此,让我们添加对
posts
的依赖:但它仍然无法正常工作。原因是它在
posts
为空时在初始渲染时触发...所以让我们添加检查“仅在加载帖子后”:现在它按预期工作并恢复滚动位置。
PS 顺便说一句,我不认为将位置写入
sessionStorage
是最好的方法。使用多个选项卡会造成混乱。如果没有示例代码,我会通过创建单独的路线“也是列表,但带有我们应该滚动到的元素的 ID”来看到替代方案。然后链接“返回列表”将定位该路线,并传递您当前正在查看详细信息的实体 ID。There are few issues here.
First:
You see, setter in
useState
does not have second argument asthis.setState()
has. But why, can you ask, yourhandleScrollPosition
is called at all?(since you can see it's called in debugger). The reason is that you've written this ashandleScrollPosition()
so it's called immediately. To demonstrate my point, if you change it to correct "passing a callback" form:As you already have in class-based version, you will see it's never called. Similarly,
will also call
handleScrollPosition()
even though obviously[].map()
does not process 6th argument.So what you should do? First, let's move scroll restoring into separate
useEffect
:obviously it did not work well, since it will be called immediately, before data is fetched. So let's add dependency on
posts
:But it will not work correctly, still. The reason is it's triggered on initial render when
posts
is empty... so let's add check "only after posts are loaded":Now it works as expected and restores scroll position.
PS btw, I don't think that writting position to
sessionStorage
is the best approach. Working with multiple tabs will make a mess. If speaking without sample code, I'd see alternative by making separate route "also the list but with ID of element we should scroll to". And then link "back to the list" will target that route, with passing of entity ID you are currently viewing details for.