我的 Next.js 应用程序的页面由 API 提供,每个页面都有一个 uri_prefix 和一个 uri。
uri_prefix 是强制性的,目前可以是 c
或 s
。但最终可以选择任何字母。
这是一个非常简单的结构:
pages
|-[prefix]
| |
| |-[slug]
处理它的 [slug].jsx 页面使用 ISG。
到目前为止,getStaticPath 回退设置为 true,因此如果管理员在后台创建新页面 (eg. {uri_prefix : c, uri : newpage1} & {uri_prefix : s, uri : newpage2})
,ISG 会生成静态 /c/newpage1
和 /s/newpage2
文件。第一次触发。
但是一旦生成,尝试诸如 /x/newpage
或 /whatever/newpage
之类的 alt url 也会启动页面,这有点出乎意料(并且不需要)。阅读文档,我认为它只允许现有的前缀。
将回退设置为 false 会禁止不需要的网址,但也需要重新构建应用,这并不方便。
我想要呈现 /c/newpage1
或 /s/newpage2
,但不是 /c/newpage2
或 /s/newpage1
(当然也不是 /somethingelse/newpage*
)。每个页面仅与其自己的前缀相关联。
我是否误解了回退的工作原理?
代码中是否有明显的错误,或者是否有另一种方法可以在没有完整构建的情况下为新页面实现 ISG,同时禁止不需要的 url?
这里是 [slug].jsx 页面:
import Layout from '@/components/Layout';
import SmallCard from '@/components/SmallCard';
import {useRouter} from 'next/router';
export default function src({products, seo}) {
const router = useRouter();
if(router.isFallback) {
return (
<h1>Loading new page...</h1>
)
}
return (
products ? (
<Layout title={seo[0].title} description={seo[0].description}>
<div>
<div className='container-fluid my-5'>
<div className="row justify-content-center">
<h1>{seo[0].h1}</h1>
</div>
<div className="row justify-content-center">
{products.map(
(product)=>(
<SmallCard product = {product}/>
)
)}
</div>
</div>
</div>
</Layout>
) : (
<Layout title={seo[0].title} description={seo[0].description}>
<h1>{seo[0].h1}</h1>
<div dangerouslySetInnerHTML={{__html: seo[0].content_front}}/>
</Layout>
)
)
}
export async function getStaticPaths() {
const resPages = await fetch(`${process.env.API_BASE_URL}/path/to/pagesapi`);
const pages = await resPages.json();
const paths = pages.map((page) => ({
params: {
prefix: page.uri_prefix,
slug: page.uri
},
}))
return {
paths,
fallback: true
};
}
export async function getStaticProps({ params: { slug } }) {
const resPages = await fetch(`${process.env.API_BASE_URL}/path/to/pagesapi`);
const pages = await resPages.json();
const seo=pages.filter(page=> page.uri == slug);
if(seo[0].src) {
const src=seo[0].src;
// get products
const resProducts = await fetch(`${process.env.API_BASE_URL_LEGACY}${src}`);
var products = await resProducts.json();
} else {
var products = null
}
return {
props: {
products,
seo
},
revalidate:60,
};
}
提前致谢。