【发布时间】:2022-12-30 13:01:57
【问题描述】:
我正在使用 nextjs 来构建目录。我实际上想单击“更多信息”和一个信息页面以加载到 /info/[id]-[first_name]-[last_name] 的 URL 下。 我通过 id 从 api 中提取数据,然后它将获取 first_name 和 last_name 数据。
我在名为 [id]-[first_name]-[last_name] 的信息文件夹中有一个文件:
export default function Info({ info }) {
return (
<div>
<h1>First Name</h1>
<p> Last Name </p>
</div>
);
}
export const getStaticPaths = async () => {
const res = await fetch('http://xxx:1337/api/info');
const data = await res.json();
// map data to an array of path objects with params (id)
const paths = [data].map(info => {
return {
params: [{
id: `${info.id}-`,
first_name: `${info.first_name}-`,
last_name: `${info.last_name}`
}]
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('http://xxxx:1337/api/info/' + id);
const data = await res.json();
return {
props: { info: data }
}
有了这个我就得到了错误:
错误:/info/[id]-[first_name]-[last_name] 的 getStaticPaths 中未提供必需参数 (id]-[first_name]-[last_name) 作为字符串
我想这个错误是不言自明的,但此时我被阻止了。我已经看到我可以使用 slug,但这意味着要重新处理很多 api。
对此的任何方向表示赞赏。谢谢!
【问题讨论】:
-
默认情况下你不能这样做,因为你不能有那种格式的路由 (
/info/[id]-[first_name]-[last_name])。但是,您可以使用rewrites和/info/[id]/[first_name]/[last_name]之类的路由来解决这个问题。见For Next.js Dynamic Routes, it is possible to combine a string with a slug?。
标签: next.js url-routing