最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to pass data between pages in Nextjs 13 with router.push()? - Stack Overflow

programmeradmin4浏览0评论

I want to programmatically pass data between pages when navigating with useRouter's push() method. The following code redirects me to the url http://localhost:3000/[object%20Object], but I was expecting it to take me to http://localhost:3000/home?userid=deepeshdm&orderid=12345. Why does it do this, and how do I fix it?

// app/page.js

"use client"
import { useRouter } from "next/navigation";

export default function Home() {

  const router = useRouter();

  const handleClick = () => {
    router.push({
      pathname: '/home',
      query: { userid: 'deepeshdm', orderid: '12345' },
    });
  };

  return (
   <>
   <h1 align="center"> Root Page </h1>  <br/>
   <button onClick={handleClick}> GO HOME </button>  <br/>
   </>
  )
}

I want to programmatically pass data between pages when navigating with useRouter's push() method. The following code redirects me to the url http://localhost:3000/[object%20Object], but I was expecting it to take me to http://localhost:3000/home?userid=deepeshdm&orderid=12345. Why does it do this, and how do I fix it?

// app/page.js

"use client"
import { useRouter } from "next/navigation";

export default function Home() {

  const router = useRouter();

  const handleClick = () => {
    router.push({
      pathname: '/home',
      query: { userid: 'deepeshdm', orderid: '12345' },
    });
  };

  return (
   <>
   <h1 align="center"> Root Page </h1>  <br/>
   <button onClick={handleClick}> GO HOME </button>  <br/>
   </>
  )
}
Share Improve this question edited Feb 7, 2023 at 15:03 Will 1,2041 gold badge13 silver badges35 bronze badges asked Feb 7, 2023 at 13:57 deepeshdmdeepeshdm 631 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

It appears for Next.js 13, router.push() only accepts a string.

It looks like they dropped pathname and query for read-only hooks.

The way around this is to use template literal string interpolation: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals

router.push(`/home?userid=${userid}&orderid=${orderid}`);

I hope this helps.

发布评论

评论列表(0)

  1. 暂无评论