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

Kau*_*Zaw 4 next.js nextjs-dynamic-routing

我有一个动态路由,我试图在 url 中显示标题并将id传递(隐藏)到我的动态路由并id在中使用getStaticProps. 我发现我无法在 nextjs 中轻松传递数据,就像我们过去使用 React Router 或其他客户端路由库传递数据一样。

我正在遵循这个答案,但是当我console.log(context.params)看不到id传递过来的内容时Link,我在这里做错了什么?

// 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: "" },
  };
}
Run Code Online (Sandbox Code Playgroud)

Psy*_*Gik 5

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

\n
    \n
  • params包含使用动态路由的页面的路由参数。例如,如果页面名称是[id].js,则params看起来像{ id: ... }。-文档
  • \n
\n
export async function getStaticProps(context) {\n  console.log(context.params); // return { movieId: \'Mortal Kombat\' }\n  return {\n    props: {}, // will be passed to the page component as props\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果动态页面看起来/pages/[movieId].js可以访问 pidcontext.params.movieId .

\n

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

\n
\n

因为getStaticProps在构建时运行,因此它不会接收仅在请求期间可用的数据,例如查询参数或 HTTP 标头,因为它会生成静态 HTML。

\n
\n

如果您需要“查询字符串”,您可以使用getServerSideProps

\n
export async function getServerSideProps(context) {\n  console.log(context.query);\n  return {\n    props: {}, // will be passed to the page component as props\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

编辑:

\n

关于这一点,您应该传递与用于动态的Link键相同的值。querypathname

\n
<Link\n  href={{\n    pathname: `/movie/[title]`,\n    query: {\n      title: movie.id, // should be `title` not `id`\n    },\n  }}\n  as={`/movie/${movie.original_title}`}\n>\n</Link>;\n
Run Code Online (Sandbox Code Playgroud)\n

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

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

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

\n