如何在Next.js的应用程序文件夹中更改和添加查询字符串?

huangapple go评论84阅读模式
英文:

How to change and add query strings in the app folder of Next.js?

问题

pages文件夹中,使用以下方式更新URL的router,我如何在app目录中更改查询参数?我使用Next.js版本13.4

英文:

With the router in pages folder, I update the url like below:

router.push({
   query: {
      ...router.query,
      page: newPage + 1
   }
})

How I can change the query parameters in the app directory? I use Next.js 13.4.

答案1

得分: 1

app文件夹中,router.push(href: string) 作为参数仅接受字符串形式的 href。你需要自己设置查询参数,就像在这个 示例 中所展示的那样。

设置方法如下:

"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";

export default function ExampleClientComponent() {
  const router = useRouter();

  const createQueryString = (name, value) => {
    const params = new URLSearchParams();
    params.set(name, value);

    return params.toString();
  };

  return (
    <>
      {/* 使用 useRouter */}
      <button
        onClick={() => {
          router.push("/posts" + "?" + createQueryString("sort", "asc"));
        }}
      >
        ASC
      </button>

      {/* 使用<Link> */}
      <Link href={"/posts" + "?" + createQueryString("sort", "desc")}>DESC</Link>
    </>
  );
}

你可以通过传递给页面组件的 searchParams 来读取它:

// app/posts/page.js

export default function Page({ searchParams }) {
  return <div>{searchParams.sort}</div>;
}

或者在任何客户端组件中使用 useSearchParams 函数:

"use client";

import { useSearchParams } from "next/navigation";

export default function Page() {
  const searchParams = useSearchParams();
  return <div>{searchParams.get("sort")}</div>;
}
英文:

In the app folder, router.push(href: string) accepts as a parameter only the href as a string. You need to set query parameters yourself, as they show in this example.

You set it this way:

&quot;use client&quot;;

import Link from &quot;next/link&quot;;
import { useRouter } from &quot;next/navigation&quot;;

export default function ExampleClientComponent() {
  const router = useRouter();

  const createQueryString = (name, value) =&gt; {
    const params = new URLSearchParams();
    params.set(name, value);

    return params.toString();
  };

  return (
    &lt;&gt;
      {/* using useRouter */}
      &lt;button
        onClick={() =&gt; {
          router.push(&quot;/posts&quot; + &quot;?&quot; + createQueryString(&quot;sort&quot;, &quot;asc&quot;));
        }}
      &gt;
        ASC
      &lt;/button&gt;

      {/* using &lt;Link&gt; */}
      &lt;Link href={&quot;/posts&quot; + &quot;?&quot; + createQueryString(&quot;sort&quot;, &quot;desc&quot;)}&gt;DESC&lt;/Link&gt;
    &lt;/&gt;
  );
}

You would read it with the searchParams passed to your page component:

// app/posts/page.js

export default function Page({ searchParams }) {
  return &lt;div&gt;{searchParams.sort}&lt;/div&gt;;
}

Or using the useSearchParams function in any client component:

&quot;use client&quot;;

import { useSearchParams } from &quot;next/navigation&quot;;

export default function Page() {
  const searchParams = useSearchParams();
  return &lt;div&gt;{searchParams.get(&quot;sort&quot;)}&lt;/div&gt;;
}

答案2

得分: 0

I wrote a function for using query strings:

export const createQueryString = (pathname, router, name: string, value: string) => {
   let searchParams = new URLSearchParams(window.location.search)
   if (value) {
      if (!Array.isArray(value)) {
         if (!searchParams.has(name)) searchParams.append(name, value)
         else searchParams.set(name, value)
      } else {
         if (!searchParams.has(name)) searchParams.append(name, value.join())
         else searchParams.set(name, value.join())
      }
   } else if (searchParams.has(name)) searchParams.delete(name)
   const newUrl = pathname + '?' + searchParams.toString()
   router.push(newUrl)
}

and in my component, I called it.
pass pathname and router from 'next/navigation' to createQueryString function:

import { createQueryString } from 'helpers'
import { usePathname, useRouter } from 'next/navigation'

const TablePagination = ({ pagination }: Props) => {
   const router = useRouter()
   const pathname = usePathname()
   return (
      <Pagination
         count={50}
         rowsPerPage={10}
         page={pagination.page - 1}
         onPageChange={(event, page) => createQueryString(pathname, router, 'page', `${page + 1}`)}
         onRowsPerPageChange={(event) =>
            createQueryString(pathname, router, 'take', event.target.value)
         }
      />
   )
}
英文:

I wrote a function for using query strings

export const createQueryString = (pathname, router, name: string, value: string) =&gt; {
   let searchParams = new URLSearchParams(window.location.search)
   if (value) {
      if (!Array.isArray(value)) {
         if (!searchParams.has(name)) searchParams.append(name, value)
         else searchParams.set(name, value)
      } else {
         if (!searchParams.has(name)) searchParams.append(name, value.join())
         else searchParams.set(name, value.join())
      }
   } else if (searchParams.has(name)) searchParams.delete(name)
   const newUrl = pathname + &#39;?&#39; + searchParams.toString()
   router.push(newUrl)
}

and in my component, I called it.
pass pathname and router from &#39;next/navigation&#39; to createQueryString function

import { createQueryString } from &#39;helpers&#39;
import { usePathname, useRouter } from &#39;next/navigation&#39;

const TablePagination = ({ pagination }: Props) =&gt; {
   const router = useRouter()
   const pathname = usePathname()
   return (
      &lt;Pagination
         count={50}
         rowsPerPage={10}
         page={pagination.page - 1}
         onPageChange={(event, page) =&gt; createQueryString(pathname, router, &#39;page&#39;, `${page + 1}`)}
         onRowsPerPageChange={(event) =&gt;
            createQueryString(pathname, router, &#39;take&#39;, event.target.value)
         }
      /&gt;
   )
}

答案3

得分: 0

这个辅助函数可以处理多个查询:

const createQueryString = useCallback(
(query) => {
const params = new URLSearchParams(searchParams);
for (const [name, value] of Object.entries(query)) {
if (name !== null && value !== undefined) {
params.set(name, value);
}
}

return params.toString();
}, [searchParams]
);

并且在客户端组件中像这样使用它:

const query = {
category: 'cars',
section: 'vehicles',
};

router.push(`/?${createQueryString(query)}`);

只需确保从 'next-navigation' 或 'next-intl/client' 中导入 router。

英文:

this helper function handle multipe queries at once:

 const createQueryString = useCallback(
(query)=&gt; {
  const params = new URLSearchParams(searchParams);
  for(const [name, value] of Object.entries(query)){
    if(name !== null &amp;&amp; value !== undefined) {
      params.set(name, value);
    }
  }
 
 return params.toString();
}, [searchParams]

);

and use it in client component like this:

 const query = {
  category: &#39;cars&#39;,
  section: &#39;vehicles&#39;,
};

router.push(`/?${createQueryString(query)}`);

just make sure that router is imported from 'next-navigation' or 'next-intl/client'

huangapple
  • 本文由 发表于 2023年5月13日 20:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定