[英]Next.js dynamic route error: The provided path `page-name` does not match the page: `/[slug]`
我正在尝试使用 [slug].js 通过 getStaticProps 和 getStaticPaths 呈现与 index.js 相邻的页面。 使用动态路由导航到页面后,出现不匹配错误。 即使提供的路径实际上与页面 slug 和页面道具内容匹配,也会发生此错误。
当 index.js 被复制并重命名为 page-name.js(例如“about.js”)时,页面呈现良好,所以我相信问题在于我如何使用 getStaticPaths。 实际上,我并没有完全理解 getStaticProps 和 getStaticPaths 之间的关系。 是否有一些映射允许引擎根据地图中的任何路径查找适当的道具?
索引.js
import Link from 'next/link';
import { getPageDataBySlug } from '../lib/api';
export default function Page(pageData) {
const page = pageData;
return (
<>
<h1>document title is: {page.documentTitle}</h1>
<Link href="/[slug]" as="/about">
<a>
<h5>Link to About</h5>
</a>
</Link>
</>
);
}
export async function getStaticProps() {
const props = await getPageDataBySlug('home');
return {
props
};
}
[slug].js
import Link from 'next/link';
import { getPageDataBySlug, getApiDataPaths } from '../lib/api';
export default function Page(pageData) {
const page = pageData;
return (
<>
<h1>document title is: {page.documentTitle}</h1>
<Link href="/" as="/">
<a>
<h5>Link to Home</h5>
</a>
</Link>
</>
);
}
// Only grab the entry for this page
export async function getStaticProps({ params }) {
const props = await getPageDataBySlug(params.slug);
return {
props
};
}
export async function getStaticPaths() {
const apiDataPaths = await getApiDataPaths();
return {
paths: apiDataPaths?.map(({ slug }) => `${slug}`) ?? [],
fallback: false
};
}
getStaticProps 返回正确的页面内容
{
"title": "About",
"slug": "about",
"description": "About page description",
"documentTitle": "Pithy Compelling Headline",
"article": {
"content": [[Object], [Object]],
}
}
getApiDataPaths() 返回
[
{ slug: 'about' },
{ slug: 'another-page' },
{ slug: 'yet-another' }
]
getStaticPaths() 映射将“路径”作为数组返回:
[
'about',
'another-page',
'yet-another'
]
我在这里缺少什么? getStaticPaths 应该只是当前页面的路径吗?
(FWIW 我使用 Contentful 作为 API,并且运行良好。)
Next Js Docs帮助查找错误。 这就是你出错的地方。 您以这种格式传入了一组对象:
[{id:1}, {id:2}]
当 getStaticPaths 期待这个时:
[
{ params: { id: '1' } },
{ params: { id: '2' } }
]
解决方案:
export async function getStaticPaths() {
const apiDataPaths = await getApiDataPaths();
// Empty arr to build new paths
const newPaths = [];
// Add params to every slug obj returned from api
for (let slug of apiDataPaths) {
newPaths.push({ params: { ...slug } });
}
// Return paths to render components
return {
paths: newPaths,
fallback: true
};
}
也可以考虑在服务器端清理数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.