NextJS | getStaticProps生成失败

时间:2020-05-19 08:03:21

标签: javascript reactjs graphql next.js react-apollo

描述错误

我对getStaticPropsApollo GraphQL有疑问。网站的一部分应该是静态页面。页面数据是通过GraphQL的{​​{1}}获取的。

要复制

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与所有slugs一起使用。然后,我使用Wordpress REST API中的slugs来获取数据。

预期行为

问题是,当我处于getStaticProps模式时,此代码有效。评论将按原样加载,并且由于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中按预期运行

系统信息

  • 操作系统:Windows 10
  • Next.js版本:9.4.0
  • Node.js版本:12.16.3

其他上下文

在项目的此阶段很难实现REST API,因此如果我们可以使development正常运行,那就太好了。

谢谢。

0 个答案:

没有答案