首页 > 解决方案 > 在 Next.JS 的 `getStaticPaths` 中设置`fallback: true` 时`throw new Error('Failed to load static props')`

问题描述

请参阅此处的讨论。我遇到了类似的错误。fallback设置为时一切正常false。但是,当 fallback 设置为 true 时,next js 会抛出错误

 throw new Error('Failed to load static props')

标签: javascriptnode.jsreactjsnext.js

解决方案


经过大量搜索和反复试验,我发现错误是由于内部抛出异常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>

推荐阅读