英文:
Shallow router push in Next.js 13 with appDir enabled
问题
In < Next 13(或禁用 appDir)中,您可以执行以下操作:
const MyComponent = () => {
const router = useRouter();
const toggleStatic = () => {
if (router.query.static) {
router.push(router.pathname, router.pathname, { shallow: true });
} else {
router.push(router.pathname, router.pathname + "static", { shallow: true });
}
}
return <>;
// ...
</>;
});
这将执行浅层路由更新,会更改位置,但不会将其推送到历史记录或触发页面加载。
现在,启用了 appDir,您需要从 next/navigation
导入函数。但是文档并未提到如何使用新路由进行浅层路由推送?
我只能做到这样:
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const toggleStatic = () => {
if (searchParams.get("static")) {
router.push(pathname);
} else {
router.push(pathname + "?static");
}
};
但这会进行完整的页面重新加载。是否有一种方法可以在 Next 13 的 appDir 中复制浅层路由的功能?
英文:
In < Next 13 (or with appDir disabled), you could do:
const MyComponent = () => {
const router = useRouter();
const toggleStatic = () => {
if (router.query.static) {
router.push(router.pathname, router.pathname, { shallow: true });
} else {
router.push(router.pathname, router.pathname + "?static", { shallow: true });
}
}
return <>
// ...
</>
});
This would perform a shallow router update that would change the location, but not push it to history or trigger a page load.
Now, with appDir enabled, you need to import functions from next/navigation
instead. But the docs don't say anything about shallow router pushing using the new router?
All I can do is this:
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const toggleStatic = () => {
if (searchParams.get("static")) {
router.push(pathname);
} else {
router.push(pathname + "?static");
}
};
But that does a full page reload. Is there a way to replicate the shallow router functionality using Next 13's appDir?
答案1
得分: 1
尝试使用replace
方法,而不是push
:
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const toggleStatic = () => {
if (searchParams.get("static")) {
router.replace(pathname);
} else {
router.replace(pathname + "?static");
}
};
英文:
Try the replace
method instead of push
:
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const toggleStatic = () => {
if (searchParams.get("static")) {
router.replace(pathname);
} else {
router.replace(pathname + "?static");
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论