在 Next.JS 中的 `getStaticPaths` 中设置 `fallback: true` 时,` throw new Error('Failed to load static props')`

may*_*513 6 javascript node.js reactjs next.js

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

 throw new Error('Failed to load static props')
Run Code Online (Sandbox Code Playgroud)

may*_*513 8

经过大量搜索和反复试验,我发现错误是因为内部抛出异常getStaticProps

为了解决这个问题,我所做的就是使用 try-catch 块。

export async function getStaticProps({ params }) {
  let data = null;
  try {
    data = await getData(params.slug);
  } catch (err) { };

  return {
    props: {
      data,
    },
  };
Run Code Online (Sandbox Code Playgroud)

当渲染时你可以使用

if(props.data) return (<your-jsx-here></your-jsx-here>)
else return <div>Any message if you want</div>
Run Code Online (Sandbox Code Playgroud)