history.replaceState() 无法在 Svelte/Sapper 中使用 history.scrollRestoration = 'auto'

history.replaceState() not working with history.scrollRestoration = 'auto' in Svelte/Sapper

我正在使用 history.replaceState() 来更新我页面的查询参数,而不会按照 this SO answer 中的建议重新加载页面。

function setQueryParam ({ name, value }) {
  const params = new URLSearchParams(window.location.search)

  params.set(name, value)
  history.replaceState({}, '', decodeURIComponent(`${window.location.pathname}?${params}`))
}

我还使用以下行存储用户的滚动位置:

history.scrollRestoration = 'auto'

从一页导航到另一页时,scrollRestoration 工作正常 - 页面之间的滚动位置保持不变。但是, 我用我的 setQueryParam 函数更改查询参数后,滚动恢复不再有效。

为什么会这样?

注意: 相同的代码在 Svelte/Sapper 之外工作正常,仅使用 HTML 和 JavaScript。

作为客户端路由器,Sapper 必须大量劫持滚动管理和恢复,以模拟您在每次页面更改时完全重新加载浏览器时通常获得的行为。

为此,uses history's state 知道要恢复的滚动位置。

当您使用 history.replaceState 时,您正在更改状态(这是您放置到 replaceState 的第一个参数)。因此,当您稍后弹出状态时,Sapper 不会找到它的恢复滚动数据。

您可以尝试像这样手动保存历史状态:

// notice the first argument
history.replaceState(history.state, '', decodeURIComponent(`${window.location.pathname}?${params}`))

我认为 history.scrollRestoration 实际上对 Sapper 没有任何影响。