【问题标题】:getting undefined data while using getStaticProps() in next.js在 next.js 中使用 getStaticProps() 时获取未定义的数据
【发布时间】:2021-03-27 11:21:33
【问题描述】:

components/featured-posts.js 中的 next.js 中使用 getStaticProps 时,我得到 Cannot read property 'map' of undefined 但如果我直接在pages/index.js 页面显示结果,有人知道它为什么这样做吗?

export async function getStaticProps(){
  const data = await fetch('http://localhost/newblog/newblogapi/posts')
  const posts=await data.json();
  return {
    props: { posts }, // will be passed to the page component as props
  }
}
const FeaturedPosts = ({posts}) => {
 
console.log(posts)

  return (
    <div className="album py-5 bg-light">
      <div className="container mt-5">
      { posts.map(post=>(
        <div key={post.id}>
        <h3>{post.title}</h3>
          </div>
      ))}
      </div>
    </div>

  );
}

export default FeaturedPosts;

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您只能在页面(/pages 目录中的文件)上使用 getStaticProps,而不能在常规 React 组件中使用。我建议您在 pages/index.js 文件中获取帖子并将它们作为道具传递给 FeaturedPosts 组件。

    【讨论】:

    • 同意。即使允许,在组件中获取数据也不是好的做法。组件应处理其实现,并将数据传递给它进行处理。
    猜你喜欢
    • 2021-10-17
    • 2023-03-19
    • 2021-12-01
    • 1970-01-01
    • 2021-10-09
    • 2021-08-10
    • 2020-12-05
    • 2021-04-27
    相关资源
    最近更新 更多