【问题标题】:restore scroll position via history push/replace state通过历史推送/替换状态恢复滚动位置
【发布时间】:2019-10-29 07:17:05
【问题描述】:

我有一个列表,我可以在其中访问我的列表项的详细视图。 在我的详细视图中,我可以在我的列表项之间导航。

我想在详细视图上有一个后退按钮,无论我在详细视图中导航的频率如何,它都能将我带到我的列表视图。

目前我试过这个: 我将一个 url: 字符串传递给我的导航组件。 这就是我列表的网址。

然后我想在单击后退按钮时更改我的状态:

 const onClickBack = () => {
        const stateData = {
            path: window.location.href,
            scrollTop: 300
        }
        window.history.replaceState(stateData, "", backURL)


        const stateData2 = {
            path: window.location.href,
            scrollTop: 300
        }

        window.history.pushState(stateData2, "", backURL)

        window.history.back()
    }

我从history pushState and scroll position复制了这段代码

无论我多久浏览一次,我现在都可以返回我的列表。但我怎样才能恢复整个状态,例如滚动位置?

我必须传递整个状态对象吗?

【问题讨论】:

    标签: reactjs routing navigation history


    【解决方案1】:

    您似乎想手动恢复滚动位置。如果是这种情况,那么您应该告诉历史 API 您的意图。

    if ('scrollRestoration' in history) {
      // Back off, browser, I got this...
      history.scrollRestoration = 'manual';
    }
    

    这样,上一个 URL 的滚动位置也会保持不变。

    文档:https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 2019-04-10
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多