[英]`throw new Error('Failed to load static props')` when setting `fallback: true` in `getStaticPaths` in Next.JS
请参阅此处的讨论。 我遇到了类似的错误。 当fallback
设置为false
时,一切正常。 但是,当 fallback 设置为 true 时,next js 会抛出错误
throw new Error('Failed to load static props')
经过大量搜索和反复试验,我发现错误是由于getStaticProps
内部抛出异常。
为了解决这个问题,我所做的就是使用 try-catch 块。
export async function getStaticProps({ params }) {
let data = null;
try {
data = await getData(params.slug);
} catch (err) { };
return {
props: {
data,
},
};
并且在渲染时可以使用
if(props.data) return (<your-jsx-here></your-jsx-here>)
else return <div>Any message if you want</div>
我在这里找到了答案https://github.com/vercel/next.js/discussions/11862 :
您的 getStaticProps 应该返回 boolean ,例如
notFound: true
,并且您的页面可以呈现 404 页面或next/error
页面。 这将允许页面最终变成真实的(如果在后端创建了缺少的 slug)。
以下是我在getStaticProps
中使用notFound: true
解决此问题的方法。
export async function getStaticProps({ params: { id } }) {
const res = await fetch(`{{api}}/items?id=${id}`);
const item = await res.json();
const notFound = item[0] ? false : true;
return {
props: {
item: item[0]
},
revalidate: 10,
notFound
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.