从 nextjs Link 组件传递数据并在 getStaticProps 中使用它

Pass data from nextjs Link component and use it in getStaticProps

我有一个动态路由,我正在尝试在 url 中显示 title 并传递(隐藏)id 到我的动态路线并在 getStaticProps 中使用 id。我发现我不能在 nextjs 中轻松传递数据,因为我们过去使用 react router 或其他客户端路由库传递数据。

我正在关注 this 答案,但是当我 console.log(context.params) 时,我看不到从 Link 传递的 id,我在这里做错了什么?

// index.js

      <Link
          href={{
            pathname: `/movie/[title]`,
            query: {
              id: movie.id, // pass the id 
            },
          }}
          as={`/movie/${movie.original_title}`}
        >
          <a>...</a>
      </Link>

// [movieId].js

export async function getStaticProps(context) {
  console.log(context.params); // return { movieId: 'Mortal Kombat' }

  return {
    props: { data: "" },
  };
}

context 参数是一个包含以下键的对象:

  • params 包含使用动态路由的页面的路由参数。例如,如果页面名称是 [id].js ,那么 params 将类似于 { id: ... }。 - Docs
export async function getStaticProps(context) {
  console.log(context.params); // return { movieId: 'Mortal Kombat' }
  return {
    props: {}, // will be passed to the page component as props
  }
}

如果动态页面看起来像 /pages/[movieId].js 您可以在 context.params.movieId .

中访问 pid

您无法访问 getStaticProps 中的“查询字符串”,因为正如文档所述,

Because getStaticProps runs at build time, it does not receive data that’s only available during request time, such as query parameters or HTTP headers as it generates static HTML.

如果需要“Query String”,可以使用getServerSideProps,

export async function getServerSideProps(context) {
  console.log(context.query);
  return {
    props: {}, // will be passed to the page component as props
  }
}

编辑:

关于 Link,您应该传递与用于动态 pathname:

query 键相同的值
<Link
  href={{
    pathname: `/movie/[title]`,
    query: {
      title: movie.id, // should be `title` not `id`
    },
  }}
  as={`/movie/${movie.original_title}`}
>
</Link>;

然后在/pages/[title].js,

export async function getStaticProps(context) {
  console.log(context.params); // return { title: 'Mortal Kombat' }
  return {
    props: {}, // will be passed to the page component as props
  }
}

请注意 title 如何用作文件名和 Link 中的查询对象的键。