【发布时间】:2021-04-18 18:15:41
【问题描述】:
我正在尝试使用 Wordpress 作为数据源来构建动态页面。
我没有得到正确的 getStaticProps 和 getStaticPaths 并导致错误
Error: The provided path `/` does not match the page: `/[slug]`.
出于测试目的,我现在已经对页面名称进行了硬编码(理想情况下,我想让它动态化)(我已经尝试为此制作代码和框,但我似乎总是在使用 next.js 和代码框时遇到问题)。
我导航到 http://localhost:3000/art-shows 进行测试
这是我的 [slug].js 页面
import Head from 'next/head'
import Link from 'next/link'
import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'
export default function Index() {
console.log(router.query)
return (
<>
<Layout>
<Head>
<title>page</title>
</Head>
<Header />
<Container>
Hello World
</Container>
</Layout>
</>
)
}
export async function getStaticProps({ params }) {
const data = await getAllPagesBySlug('/art-shows')
return {
props: {
page: data.page,
},
}
}
export async function getStaticPaths() {
const allPages = await getAllPagesWithSlug()
return {
paths: allPages.edges.map(({ node }) => `${node.uri}`) || [],
fallback: true,
}
}
这是我的连接../lib/api'
const API_URL = process.env.WORDPRESS_API_URL
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' }
if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
headers[
'Authorization'
] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
}
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
export async function getAllPagesBySlug($id) {
const data = await fetchAPI(`
{
page(id: $id, idType: URI) {
content
isFrontPage
isPostsPage
uri
title(format: RAW)
seo {
title
metaDesc
metaRobotsNofollow
metaRobotsNoindex
}
featuredImage {
node {
sourceUrl
}
}
}
}
`)
return data
}
export async function getAllPagesWithSlug() {
const data = await fetchAPI(`
{
pages(first: 10000) {
edges {
node {
uri
}
}
}
}
`)
return data?.pages
}
【问题讨论】: