如何访问 Next.js 中 getServerSideProps 内的查询参数?

viv*_* kn 7 javascript reactjs next.js

我试图getServerSideProps在我的代码中使用 get ,但我无法做到这一点,因为我无法通过router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的 https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

我是 Next.js 的新手,而且我对 Next.js 没有太多了解,所以请不要告诉我阅读文档,如果我理解文档,我就不会问这个问题。

iam*_*ynq 11

您应该使用 getServerSideProps 中的上下文来获取查询参数

export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
Run Code Online (Sandbox Code Playgroud)


小智 7

useRouter 用于客户端路由,可以在客户端使用,而 getServerSideProps 将在服务器端执行。

由于这个原因,你不能在 getServerSideProps 中使用 useRouter() 。

如果你想访问 getServerSideProps 中的查询参数,那么你可以使用 context.query.[parameter],所以你的代码将如下所示

export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
Run Code Online (Sandbox Code Playgroud)