如何从useRouter()hock中查询项目,以防我使用nextjs和App Router方法[重复]

ztigrdn8  于 2023-06-22  发布在  其他
关注(0)|答案(3)|浏览(113)

此问题已在此处有答案

Read URL dynamic parameter/slug with Next.js in the app folder(1个答案)
How to get the current pathname in the app directory of Next.js 13?(1个答案)
9天前关闭

这是使用Pages Router的方法

import { useRouter } from "next/router";

import React from "react";

function ShowroomListings({}) {
  const router = useRouter();
  const { listingId } = router.query as { listingId: string };

  return <div>This is item No. {listingId}</div>;
}

export default ShowroomListings;

Failed to compile message
现在我这次从“next/navigation”导入useRouter,但是'.query'将不再工作

import { useRouter } from "next/navigation";

import React from "react";

function ShowroomListings({}) {
  const router = useRouter();
  const { listingId } = router.query as { listingId: string };

  return <div>This is item No. {listingId}</div>;
}

export default ShowroomListings;
fdx2calv

fdx2calv1#

useRouter只适用于客户端组件(而您的组件是服务器组件)。您可以将'use client'指令添加到文件的顶部以使用useRouter
更新:

  • query对象已被删除,替换为useSearchParams

参考文献:

  1. Next.js useRouter
  2. Next.js 'use client'指令
  3. Next.js useSearchParams
qojgxg4l

qojgxg4l2#

对我很有效

import React from "react";

type ShowroomProps = {
  params: {
    listingId: string;
  };
};

export default function ShowroomListings({
  params: { listingId },
}: ShowroomProps) {
  return <div>This is item No. {listingId}</div>;
}

传递正确的动态路由值

polkgigr

polkgigr3#

不能在服务器组件中使用useRouter钩子,因为它是客户端钩子。您需要使您的组件客户端,以便获得查询参数。

'use client'

nextjs还为查询参数引入了新的钩子,即useSearchParams,你可以很容易地获得查询参数。

const params = useSearchParms()
params.get("query-parameter-name")

相关问题