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)
这context参数是一个包含以下键的对象:
params包含使用动态路由的页面的路由参数。例如,如果页面名称是[id].js,则params看起来像{ id: ... }。-文档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}\nRun Code Online (Sandbox Code Playgroud)\n如果动态页面看起来/pages/[movieId].js可以访问 pidcontext.params.movieId .
您无法访问“查询字符串”getStaticProps因为正如文档所述,
\n\n因为
\ngetStaticProps在构建时运行,因此它不会接收仅在请求期间可用的数据,例如查询参数或 HTTP 标头,因为它会生成静态 HTML。
如果您需要“查询字符串”,您可以使用getServerSideProps,
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}\nRun Code Online (Sandbox Code Playgroud)\n关于这一点,您应该传递与用于动态的Link键相同的值。querypathname:
<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>;\nRun Code Online (Sandbox Code Playgroud)\n然后在/pages/[title].js,
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}\nRun Code Online (Sandbox Code Playgroud)\n请注意如何title在文件名和查询对象中用作键Link.
| 归档时间: |
|
| 查看次数: |
21059 次 |
| 最近记录: |