首页 > 解决方案 > NextJS | getStaticProps 在构建时失败

问题描述

描述错误

我有一个问题getStaticPropsApollo GraphQL。网站的一部分应该是静态页面。GraphQL使用from获取页面数据Wordpress CMS

重现

export const getStaticPaths = async () => {
  // Call an external API endpoint to get posts
  const res = await fetch("https://wordpress/posts")
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id, slug: post.slug },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}
export const getStaticProps = async ({ params }) => {
  const apolloClient = createApolloClient()
  const { data } = await apolloClient.query({
    query: single_review_query,
    variables: { slug: params.slug },
  })

  const reviewBy = data.reviewBy

  return { props: { reviewBy } }
}
const Review = ({ reviewBy }) => {
  console.log(reviewBy )

  return (
    <Layout>
        // Content populated by {reviewBy} goes here
    </Layout>
  )
}

getStaticPaths代码中,我得到了所有的slugswith Wordpress REST API。然后我使用它们slugsgetStaticProps获取数据。

预期行为

问题是这段代码在我处于development模式时有效。评论按应有的方式加载,内容登录console到期console.log(reviewBy)。当我使用yarn build时出现问题。我在控制台中收到此错误

Error occurred prerendering page "/review/review-title-goes-here". Read more: https://err.sh/next.js/prerender-error:
TypeError: Cannot read property 'title' of null

它无法加载标题。标题加载了reivewBy.title. 如果我将其注释掉,它只会在下一段加载数据的代码上抛出错误,reviewBy依此类推,而它按预期工作development

系统信息

附加上下文

REST API 在项目的这个阶段将很难实现,所以如果我们能够工作,那就太好GraphQL了。

先感谢您。

标签: javascriptreactjsgraphqlnext.jsreact-apollo

解决方案


推荐阅读