首页 > 解决方案 > 为什么使用 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,最初是enableRegenis true,但该文件被第二次命中,enableRegen然后是undefinedeftFileId总是被填充。

如果我在页面上进行硬刷新,并且不通过 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 生态系统中,但不知道该怎么办。有任何想法吗?

标签: next.js

解决方案


useRouter仅适用于路径,不解析查询参数。

我建议您使用window.location以获取搜索参数,然后使用URLSearchParams. 当然,检查window对象是否存在:

let enableGen = false

if (typeof window !== "undefined") {
  const params = new URLSearchParams(window.location.search)
  enableGen = params.get("enableRegen")
}

推荐阅读