本文介绍了NextJS:当回退设置为 true 时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using vercel for NextJS and this is my setup in getStaticPaths

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

  return { paths, fallback: true }

当我将回退设置为 true 时,我在 vercel 中遇到此错误:

When I set the fallback to true, I have got this error in vercel:

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

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

It is ok when fallback is set to false but I really like to set fallback set to true so that pages can be updated frequently. Any help will be greatly appreciated...

推荐答案

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

Inside your /clip/[player]/[id].js file, you need to handle the fallback state when that page is being requested on-demand.

// 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

这篇关于NextJS:当回退设置为 true 时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:38