互換的青春
2023-03-10 15:12:11
我正在嘗試使用[slug].js來呈現與index.jsviagetStaticProps和相鄰的頁面getStaticPaths。使用動態路由導航到頁面后,出現不匹配錯誤。即使提供的路徑實際上與頁面 slug 和頁面道具內容匹配,也會發生此錯誤。當index.js復制并重命名為page-name.js(例如about.js)時,頁面呈現良好,所以我認為問題在于我如何使用getStaticPaths. 實際上,我并沒有完全理解getStaticProps和之間的關系getStaticPaths。是否有一些映射允許引擎在給定地圖中的任何路徑的情況下查找適當的道具?Index.jsimport 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].jsimport 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 pageexport 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,并且運行良好。
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
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
};
}
您還可以考慮清理服務器端的數據。
添加回答
舉報
0/150
提交
取消