首页 > 解决方案 > NextJS:当回退设置为 true 时失败

问题描述

我正在为 NextJS 使用 vercel,这是我在 getStaticPaths 中的设置

  const paths = posts.map((post) => ({
    params: { player: post.player, id: post.id },
  }))

  return { paths, fallback: true }

当我将后备设置为 true 时,我在 vercel 中遇到了这个错误:

21:55:01.736 信息 - 生成静态页面 (1752/1752) 21:55:01.736 > 发生构建错误 21:55:01.739 错误:导出在以下路径上遇到错误:21:55:01.739 /clip/[player]/ [ID]

当 fallback 设置为 false 时可以,但我真的很喜欢将 fallback 设置为 true 以便页面可以经常更新。任何帮助将不胜感激...

标签: javascriptreactjsnext.jsvercel

解决方案


在您的/clip/[player]/[id].js文件中,您需要在按需请求该页面时处理回退状态。

// pages/posts/[id].js
import { useRouter } from 'next/router'

function Post({ post }) {
  const router = useRouter()

  // If the page is not yet generated, this will be displayed
  // initially until getStaticProps() finishes running
  if (router.isFallback) {
    return <div>Loading...</div>
  }

  // Render post...
}

// This function gets called at build time
export async function getStaticPaths() {
  return {
    // Only `/posts/1` and `/posts/2` are generated at build time
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    // Enable statically generating additional pages
    // For example: `/posts/3`
    fallback: true,
  }
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return {
    props: { post },
    // Re-generate the post at most once per second
    // if a request comes in
    revalidate: 1,
  }
}

export default Post

https://nextjs.org/docs/basic-features/data-fetching#fallback-true


推荐阅读