我正在使用NextJS将数据的CSV转换为静态页面。每一页都是pages/[slug].jsx。我正在对toLowerCase()调用slug.jsx、getStaticPaths()和getStaticProps()函数中的段塞值。生成的页面为小写。例如,/ab101、/ab102、/cc500都会解析到页面/slg.jsx页面。
不幸的是,人们可能会手动输入的url,并可能使用大写或混合大小写作为段塞值,目前产生的结果是404。
问:如何使路由大小写对段塞值不敏感?
更新
当我从fallback: true返回getStaticPaths()时,即使没有完全匹配的路径,[slug].jsx文件也会被击中。然后,我可以检查isFallback,如下面Antony所示。
此外,当没有找到页面时,传递给我的页面的items参数将是未定义的。路由器的pathname值是"/[slug]",而不是“片段”的值。然而,有一个asPath值包含有用的数据,例如/mixedCaseSlug?param=value&foo=bar。
当页面呈现时,我检查它是否是回退。如果是的话,显示装载..。消息。下一步将显示这一点,并调用getStaticProps()来生成“缺失”页面。然后,使用页面数据重新呈现。在getStaticProps无法获得页面数据的情况下,我推送一条路径,该路径将导致内置404页。
export default function Page({ item }) {
const { isFallback, push } = useRouter()
const hasPageData = item && Object.keys(item).length > 0
useEffect(() => {
if (!isFallback && !hasPageData) {
push('/page-not-found/error')
}
}, [isFallback, hasPageData])
const loadingMsg = <div>Loading...</div>
const notFoundMsg = <div>Page not found</div>
return isFallback ? loadingMsg : hasPageData ? <Item item={item} /> : notFoundMsg
}我需要将getStaticProps()更新为小写的slug param,因为它现在可能是混合大小写,但是我们希望找到我们的页面数据。我需要考虑到这样的情况,因为没有关于鼻涕虫的数据。
export async function getStaticProps({ params }) {
const { slug } = params
const item = data.find(o => o.Practice_Code.trim().toLowerCase() === slug.toLowerCase())
return {
props: {
item: item ? item : {}
}
}
}这一切看起来都很疯狂,所以我仍然在想,是否有更好的方法。
发布于 2021-06-24 17:43:07
NextJS路由是sensitive.You可以在getStaticPaths中使用回退属性来捕获与默认情况下在getStaticPaths中提供的路由不同的路由。
编辑:我已经根据与戴夫的讨论更新了答案。
我们可以给回退:真或回退:“阻塞”,如果我们给回退:真,我们可以显示一个自定义组件,直到时间页是loaded.For回退:“阻塞”新路径不由getStaticPaths返回将等待生成
当我们给回:真或“阻塞”静态页面将生成时,用户第一次访问该网站和生成的网页将被服务为进一步的访问。
样本代码
export async function getStaticPaths() {
const idList = await fetchAllIds();
const paths = [
];
idList.forEach((id) => {paths.push(`/posts/${id}`)})
return { paths, fallback: true };
}我们注意到,getStaticProps中的代码应该不区分大小写以获取数据,而不管url中提供的数据是什么。
export async function getStaticProps({ params }) {
const { slug } = params;
try {
/// This fetch api should be able to fetch the data irrespective of the case of the slug
or we should convert it to the required case before passing it as a parameter to API
const data= await fetchSlugDetails(slug);
//Same logic should be performed if you are getting data filtered based on slug from an existing array.
return data? { props: { data} } : { notFound: true };
} catch (error) {
console.error(error);
return { notFound: true };
}
}注意:如果您使用fallback:true,则必须处理notfound情况和回退情况。对于回退,在静态生成页面时,您可以从next/ isFallback获得值
https://stackoverflow.com/questions/68116403
复制相似问题