使用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
相关产品推荐
相关产品推荐

