next.js - 为什么使用 useRouter 时我的查询参数不存在?下一个
问题描述
我有一条被击中的 nextjs 路线。这是网址
localhost:8080/eft-files/133722?enableRegen=true
.
在我的/pages
文件夹中,这是我用来获取查询参数的代码。
const EftFileViewWrapper = () => {
const {
query: { eftFileId, enableRegen }
} = useRouter();
return (
<EftFileView
eftFileId={eftFileId}
enableRegen={enableRegen}
/>
);
};
当应用程序通过 a 路由时next/link
,最初是enableRegen
is true
,但该文件被第二次命中,enableRegen
然后是undefined
。 eftFileId
总是被填充。
如果我在页面上进行硬刷新,并且不通过 a 路由到它next/link
,我总是会为所有查询参数获得正确的值。
我不得不使用它URLSearchParams
来完成这项工作,如下所示:
const EftFileViewWrapper = () => {
const {
query: { eftFileId, enableRegen }
} = useRouter();
let params = isInBrowser && new URLSearchParams(location.search);
return (
<EftFileView
eftFileId={eftFileId}
enableRegen={enableRegen || params.get("enableRegen")}
/>
);
};
我宁愿留在 nextjs 生态系统中,但不知道该怎么办。有任何想法吗?
解决方案
useRouter
仅适用于路径,不解析查询参数。
我建议您使用window.location
以获取搜索参数,然后使用URLSearchParams
. 当然,检查window
对象是否存在:
let enableGen = false
if (typeof window !== "undefined") {
const params = new URLSearchParams(window.location.search)
enableGen = params.get("enableRegen")
}
推荐阅读
- c# - 如何确保从抽象泛型类派生的类将自身用作泛型参数
- c# - 如何使用 powershell 从非提升的 .NET 应用程序预配 UWP 应用程序
- excel - 在 Pandas 中转置数据
- spring-integration - 如何在spring集成数据库轮询器中从多个表中获取数据
- ios - SWIFT:navigationviewcontroller 不会将应用程序转换到另一个视图控制器
- regex - 一次匹配 2 个模式的正则表达式或匹配两者的 Applescript 中的 SED
- reactjs - InAppBrowser 未在 Ionic React App 中打开
- ansible - Ansible Jinja2 模板循环迭代
- html - 阻止 VSCode 在“#”符号后“绿化”我的 Dust / HTML 代码
- android - 使用导航组件在堆栈中添加片段链