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

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

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:

  1. router.push({
  2. query: {
  3. ...router.query,
  4. page: newPage + 1
  5. }
  6. })

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。你需要自己设置查询参数,就像在这个 示例 中所展示的那样。

设置方法如下:

  1. "use client";
  2. import Link from "next/link";
  3. import { useRouter } from "next/navigation";
  4. export default function ExampleClientComponent() {
  5. const router = useRouter();
  6. const createQueryString = (name, value) => {
  7. const params = new URLSearchParams();
  8. params.set(name, value);
  9. return params.toString();
  10. };
  11. return (
  12. <>
  13. {/* 使用 useRouter */}
  14. <button
  15. onClick={() => {
  16. router.push("/posts" + "?" + createQueryString("sort", "asc"));
  17. }}
  18. >
  19. ASC
  20. </button>
  21. {/* 使用<Link> */}
  22. <Link href={"/posts" + "?" + createQueryString("sort", "desc")}>DESC</Link>
  23. </>
  24. );
  25. }

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

  1. // app/posts/page.js
  2. export default function Page({ searchParams }) {
  3. return <div>{searchParams.sort}</div>;
  4. }

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

  1. "use client";
  2. import { useSearchParams } from "next/navigation";
  3. export default function Page() {
  4. const searchParams = useSearchParams();
  5. return <div>{searchParams.get("sort")}</div>;
  6. }
英文:

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:

  1. &quot;use client&quot;;
  2. import Link from &quot;next/link&quot;;
  3. import { useRouter } from &quot;next/navigation&quot;;
  4. export default function ExampleClientComponent() {
  5. const router = useRouter();
  6. const createQueryString = (name, value) =&gt; {
  7. const params = new URLSearchParams();
  8. params.set(name, value);
  9. return params.toString();
  10. };
  11. return (
  12. &lt;&gt;
  13. {/* using useRouter */}
  14. &lt;button
  15. onClick={() =&gt; {
  16. router.push(&quot;/posts&quot; + &quot;?&quot; + createQueryString(&quot;sort&quot;, &quot;asc&quot;));
  17. }}
  18. &gt;
  19. ASC
  20. &lt;/button&gt;
  21. {/* using &lt;Link&gt; */}
  22. &lt;Link href={&quot;/posts&quot; + &quot;?&quot; + createQueryString(&quot;sort&quot;, &quot;desc&quot;)}&gt;DESC&lt;/Link&gt;
  23. &lt;/&gt;
  24. );
  25. }

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

  1. // app/posts/page.js
  2. export default function Page({ searchParams }) {
  3. return &lt;div&gt;{searchParams.sort}&lt;/div&gt;;
  4. }

Or using the useSearchParams function in any client component:

  1. &quot;use client&quot;;
  2. import { useSearchParams } from &quot;next/navigation&quot;;
  3. export default function Page() {
  4. const searchParams = useSearchParams();
  5. return &lt;div&gt;{searchParams.get(&quot;sort&quot;)}&lt;/div&gt;;
  6. }

答案2

得分: 0

I wrote a function for using query strings:

  1. export const createQueryString = (pathname, router, name: string, value: string) => {
  2. let searchParams = new URLSearchParams(window.location.search)
  3. if (value) {
  4. if (!Array.isArray(value)) {
  5. if (!searchParams.has(name)) searchParams.append(name, value)
  6. else searchParams.set(name, value)
  7. } else {
  8. if (!searchParams.has(name)) searchParams.append(name, value.join())
  9. else searchParams.set(name, value.join())
  10. }
  11. } else if (searchParams.has(name)) searchParams.delete(name)
  12. const newUrl = pathname + '?' + searchParams.toString()
  13. router.push(newUrl)
  14. }

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

  1. import { createQueryString } from 'helpers'
  2. import { usePathname, useRouter } from 'next/navigation'
  3. const TablePagination = ({ pagination }: Props) => {
  4. const router = useRouter()
  5. const pathname = usePathname()
  6. return (
  7. <Pagination
  8. count={50}
  9. rowsPerPage={10}
  10. page={pagination.page - 1}
  11. onPageChange={(event, page) => createQueryString(pathname, router, 'page', `${page + 1}`)}
  12. onRowsPerPageChange={(event) =>
  13. createQueryString(pathname, router, 'take', event.target.value)
  14. }
  15. />
  16. )
  17. }
英文:

I wrote a function for using query strings

  1. export const createQueryString = (pathname, router, name: string, value: string) =&gt; {
  2. let searchParams = new URLSearchParams(window.location.search)
  3. if (value) {
  4. if (!Array.isArray(value)) {
  5. if (!searchParams.has(name)) searchParams.append(name, value)
  6. else searchParams.set(name, value)
  7. } else {
  8. if (!searchParams.has(name)) searchParams.append(name, value.join())
  9. else searchParams.set(name, value.join())
  10. }
  11. } else if (searchParams.has(name)) searchParams.delete(name)
  12. const newUrl = pathname + &#39;?&#39; + searchParams.toString()
  13. router.push(newUrl)
  14. }

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

  1. import { createQueryString } from &#39;helpers&#39;
  2. import { usePathname, useRouter } from &#39;next/navigation&#39;
  3. const TablePagination = ({ pagination }: Props) =&gt; {
  4. const router = useRouter()
  5. const pathname = usePathname()
  6. return (
  7. &lt;Pagination
  8. count={50}
  9. rowsPerPage={10}
  10. page={pagination.page - 1}
  11. onPageChange={(event, page) =&gt; createQueryString(pathname, router, &#39;page&#39;, `${page + 1}`)}
  12. onRowsPerPageChange={(event) =&gt;
  13. createQueryString(pathname, router, &#39;take&#39;, event.target.value)
  14. }
  15. /&gt;
  16. )
  17. }

答案3

得分: 0

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

  1. const createQueryString = useCallback(
  2. (query) => {
  3. const params = new URLSearchParams(searchParams);
  4. for (const [name, value] of Object.entries(query)) {
  5. if (name !== null && value !== undefined) {
  6. params.set(name, value);
  7. }
  8. }
  9. return params.toString();
  10. }, [searchParams]
  11. );

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

  1. const query = {
  2. category: 'cars',
  3. section: 'vehicles',
  4. };
  5. router.push(`/?${createQueryString(query)}`);

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

英文:

this helper function handle multipe queries at once:

  1. const createQueryString = useCallback(
  2. (query)=&gt; {
  3. const params = new URLSearchParams(searchParams);
  4. for(const [name, value] of Object.entries(query)){
  5. if(name !== null &amp;&amp; value !== undefined) {
  6. params.set(name, value);
  7. }
  8. }
  9. return params.toString();
  10. }, [searchParams]

);

and use it in client component like this:

  1. const query = {
  2. category: &#39;cars&#39;,
  3. section: &#39;vehicles&#39;,
  4. };
  5. 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:

确定