【发布时间】:2021-01-03 17:40:22
【问题描述】:
我正在尝试使用[slug].js 通过getStaticProps 和getStaticPaths 呈现与index.js 相邻的页面。使用动态路由导航到页面后,我收到不匹配错误。即使提供的路径确实与页面 slug 和页面道具内容匹配,也会发生此错误。
当index.js 被复制并重命名为page-name.js(例如about.js)时,页面呈现良好,所以我认为问题在于我如何使用getStaticPaths。实际上,我并不完全理解getStaticProps 和getStaticPaths 之间的关系。是否有一些映射允许引擎在给定地图中的任何路径的情况下查找适当的道具?
Index.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() 映射以数组形式返回 paths:
[
'about',
'another-page',
'yet-another'
]
我在这里缺少什么? getStaticPaths应该只是当前页面的路径吗?
FWIW 我使用 Contentful 作为 API,并且运行良好。
【问题讨论】:
标签: javascript next.js