如何使用’next/navigation’中的useRouter将一个对象传递到另一个页面?

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

How to pass an object to another page using the useRouter from 'next/navigation'?

问题

我在一页上,想要将用户重定向到另一页。
我想使用来自next/navigationuseRouter钩子来向新页面发送一个对象,因为我正在使用应用程序目录。如何更改下面的代码以传递一个对象?

import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/dashboard')

如果我使用页面目录,我会这样做:

import { useRouter } from 'next/router'
const router = useRouter()
router.push({
  pathname: '/dashboard',
  query: { key: value },
})

我在文档中没有找到如何实现这一点。

英文:

I am on one page, and I want to redirect the user to another page.
I would like to send an object to the new page using the hook useRouter from next/navigation because I'm using the app directory. How can I change the code below to pass an object?

import { useRouter } from 'next/navigation'  
const router = useRouter()
router.push('/dashboard')

If I were using the page directory, I would do it like this:

import { useRouter } from 'next/router'  
const router = useRouter()
router.push({
  pathname: '/dashboard',
  query: {key : value},
})

I didn't find how to do it in the docs.

答案1

得分: 1

app文件夹中,router.push(href: string)仅接受href作为字符串参数。如果您需要查询字符串,您需要自行设置,就像这个示例中所示。

在您的情况下,可以这样做:

"use client";

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 (
    <button
      onClick={() => {
        router.push("/dashboard" + "?" + createQueryString("key", "value"));
      }}
    >
      Redirect with a query parameter
    </button>
  );
}

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

// app/dashboard/page.js

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

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

"use client";

import { useSearchParams } from "next/navigation";

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

⚠️:查询参数是字符串。您可以一次传递多个参数。但如果您需要将对象传递给一个键,您需要使用params.set("key", JSON.stringify(value))

在使用它的另一侧使用之前,请调用JSON.parse对值进行解析。

英文:

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

In your case, it can be like so:

&quot;use client&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;button
      onClick={() =&gt; {
        router.push(&quot;/dashboard&quot; + &quot;?&quot; + createQueryString(&quot;key&quot;, &quot;value&quot;));
      }}
    &gt;
      Redirect with a query parameter
    &lt;/button&gt;
  );
}

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

// app/dashboard/page.js

export default function Page({ searchParams }) {
  return &lt;div&gt;{searchParams.key}&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;key&quot;)}&lt;/div&gt;;
}

⚠️: query parameters are stings. You can pass multiple at once. But if you need to pass an object to one key, you need to params.set(&quot;key&quot;, JSON.stringify(value)).
And call JSON.parse on the value before using it on the other side.

huangapple
  • 本文由 发表于 2023年8月10日 20:30:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875755.html
匿名

发表评论

匿名网友

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

确定