【问题标题】:`throw new Error('Failed to load static props')` when setting `fallback: true` in `getStaticPaths` in Next.JS在 Next.JS 的 `getStaticPaths` 中设置`fallback: true` 时`throw new Error('Failed to load static props')`
【发布时间】:2021-08-28 22:35:25
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js reactjs next.js


    【解决方案1】:

    经过大量搜索和反复试验,我发现错误是因为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>
    

    【讨论】:

      【解决方案2】:

      我在这里找到了答案https://github.com/vercel/next.js/discussions/11862

      您的 getStaticProps 应该返回一个类似 notFound: true 的布尔值,并且您的页面可以呈现 404 页面或 next/error 页面。这将使页面最终变成真实的(如果在后端创建缺少的 slug)。

      【讨论】:

        猜你喜欢
        • 2021-09-10
        • 1970-01-01
        • 2020-08-03
        • 2021-08-05
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多