【发布时间】:2020-09-08 21:26:57
【问题描述】:
在 Next.js 中尝试使用动态路由进行浅层路由时,页面会刷新并忽略浅层。似乎很多人对此感到困惑。
假设我们从下一页开始
router.push(
'/post/[...slug]',
'/post/2020/01/01/hello-world',
{ shallow: true }
);
然后我们路由到另一篇博文:
router.push(
'/post/[...slug]',
'/post/2020/01/01/foo-bar',
{ shallow: true }
);
这样不触发浅路由,浏览器刷新,为什么?
在代码库中很清楚这是一个特性:
// If asked to change the current URL we should reload the current page
// (not location.reload() but reload getInitialProps and other Next.js stuffs)
// We also need to set the method = replaceState always
// as this should not go into the history (That's how browsers work)
// We should compare the new asPath to the current asPath, not the url
if (!this.urlIsNew(as)) {
method = 'replaceState'
}
我可以使用window.history.pushState() 手动实现相同的目的,尽管这当然是个坏主意:
window.history.pushState({
as: '/post/2020/01/01/foo-bar',
url: '/post/[...slug]',
options: { shallow: true }
}, '', '/post/2020/01/01/foo-bar');
由于 Next.JS 的内部 API 可能随时更改...我可能会遗漏一些东西...但是为什么在这种情况下会忽略浅层?看起来很奇怪。
【问题讨论】:
-
我遇到了同样的问题,我现在寻求您的解决方案,但我仍然觉得它是一个黑客:/
-
我在下一个 github 讨论部分发布了一个未解决的问题
-
问题的根源可能在组件中或在渲染它的路径中。您能否分享一下您的路由器和组件的代码?
-
不,这是该功能在 NextJS 中的工作方式。它记录在代码中。
-
似乎只有当动态路由被设计为“新页面”时才会发生,正如他们在caveats 中提到的那样。很难说为什么没有官方回应,但我猜动态路由的数据需求可能会发生很大变化,因为它们可能涵盖“全部”情况。在旁注中,
Router.push('/post/[...slug]', '/post/2020/01/01/foo-bar')是否表现出相同的行为?
标签: javascript reactjs routes next.js server-side-rendering