You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用router.replace时,如何阻止滚动位置自动回到顶部?

问题描述

使用useRouter的router.replace方法修改当前URL时,页面滚动位置会自动回到顶部,但使用原生History API的history.replaceState则不会出现这个问题。

滚动位置回到顶部的代码:

if (process.client) {
  setTimeout(() => {
    router.replace('?thing=ok');
  }, 4000);
}

滚动位置保持不变的代码:

if (process.client) {
  setTimeout(() => {
     history.replaceState(null, null, '?thing=ok');
  }, 4000);
}
解决方案

在Next.js的useRouter中,router.replace默认会触发滚动到顶部的行为,只需在调用时传入scroll: false配置项即可阻止这一默认行为:

if (process.client) {
  setTimeout(() => {
    router.replace('?thing=ok', undefined, { scroll: false });
  }, 4000);
}

router.replace的第三个参数是可选配置对象,设置scroll: false后,路由跳转时就不会自动将页面滚动到顶部,行为和原生history.replaceState完全一致。

内容的提问来源于stack exchange,提问作者Galivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 10:49:53