gpt4 book ai didi

next.js - 在 getStaticProps 中使用路由器

转载 作者:行者123 更新时间:2023-12-04 00:56:34 33 4
gpt4 key购买 nike

我正在尝试从一个因 URL 而异的 API 中获取数据,尝试使用 withRouter 来完成它,但它似乎在 getStaticProps 中不起作用。

我目前有以下代码:

export async function getStaticProps({ router }) {
const pageRequest = `http://localhost:3000/api/posts/${router.query.pid}`
const res = await fetch(pageRequest)
const json = await res.json()
return {
props: {
json,
},
}
}

它回来了:
TypeError: Cannot read property 'query' of undefined

获取 URL 中的变量以在 getStaticProps 中使用的正确方法是什么?

最佳答案

getStaticProps在构建时调用 .您没有路由器,因为没有执行任何请求。

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

export async function getStaticProps(context) {
const pid = context.params.pid
return {
props: {}, // will be passed to the page component as props
}
}

请注意,使用 带有动态路由的静态导出需要 getStaticPaths .您需要预先指定所有可能的 ID,以便 Next.js 知道要生成哪些页面。
export async function getStaticPaths() {
return {
paths: [
{ params: { pid: '1' } },
{ params: { pid: '2' } }
],
fallback: true or false // See the "fallback" section below
};
}

另外, 你不能在 getStaticProps 中调用你自己的 API 因为它是在构建时执行的(没有服务器在运行)。您可以直接从数据库中获取数据,而无需 API 调用。

我建议阅读 Next.js Data fetching有关更多示例和详细信息。

或者,您可以改为在客户端获取数据。

Fetching data on the client side

getStaticProps

关于next.js - 在 getStaticProps 中使用路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62143824/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com