如何在使用 router.push 时隐藏 URL 中的查询参数?

Ish*_*rat 14 reactjs next.js next-router

我通过查询参数将一些数据从一个页面传递到另一个页面,但我想隐藏 URL 中的查询。

这是我的代码。

import { useRouter } from "next/router";

const handleFormSubmit = async (values) => {
    const res = await AuthService.login(values.email, values.password);

    if (res.status === 200) {
   
       if (res.data.is_phone_number_exists === 1 && res.data.is_phone_number_verified === 0) {
        router.push({
          pathname: '/otp-verification',
          query: { email: values.email, password: values.password, phone_number: res.data.phone_number} //I want hide this query part from the url
        }) 
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

如何在使用时隐藏 URL 中的查询参数router.push()?或者还有其他方法可以做同样的事情吗?

jul*_*ves 42

使用 时,您可以使用调用中的next/router第二个参数传递查询参数,而无需在地址栏上可见。asrouter.push

router.push({
    pathname: '/otp-verification',
    query: { email: values.email, password: values.password, phone_number: res.data.phone_number }
}, '/otp-verification')
Run Code Online (Sandbox Code Playgroud)


Anu*_*thi 6

您也可以使用asprops 来隐藏查询参数。next/link例如:

<Link href={`/blogs/${item.slug}?id=${item.id}`} as={`/blogs/${item.slug}`} passHref>
    <a href="" className="hover:text-cyanBlue">
        Read More
    </a>
</Link>
Run Code Online (Sandbox Code Playgroud)

请记住,如果您将 target="_blank" 设置为锚标记或打开浏览器下一个选项卡的链接,则此操作将不起作用。