简体   繁体   English

在 next.js 中使用 getStaticProps() 时获取未定义的数据

[英]getting undefined data while using getStaticProps() in next.js

I am getting Cannot read property 'map' of undefined when using getStaticProps in next.js inside components/featured-posts.js but if i use it directly on pages/index.js page it shows the results, anybody know why its doing this?我在components/featured-posts.js内部的 next.js 中使用 getStaticProps 时无法读取未定义的属性“映射”,但如果我直接在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;

You can only use getStaticProps on pages (files in the /pages directory), not in regular React components.您只能在页面(/pages 目录中的文件)上使用 getStaticProps,而不能在常规 React 组件中使用。 I suggest you get the posts in your pages/index.js file and pass them as props to the FeaturedPosts component.我建议您在 pages/index.js 文件中获取帖子并将它们作为道具传递给 FeaturedPosts 组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在尝试循环下一个 js 页面中的数据(使用 getStaticProps)时我得到未定义? - Why am I getting undefined when attempting to loop over data in next js page (using getStaticProps)? 错误:如何序列化来自 getStaticProps 的数据:Next.js - Error: How to serialize data from getStaticProps : Next.js 错误:如何从 Next.js 中的 getStaticProps 序列化数据 - Error: How to serialize data from getStaticProps in Next.js Next.js ISR 将附加数据从 getStaticPaths 传递给 getStaticProps - Next.js ISR pass additional data to getStaticProps from getStaticPaths 访问 Next.js 中 map 中的数据 object 的值时出现未定义 - Getting Undefined while accessing the values of data object inside map in Next.js HOC 中的 getStaticProps 在 Next.js 中不起作用 - getStaticProps in HOC not working in Next.js 为什么 getStaticProps() 在 Next.js 中是一个异步函数? - Why is getStaticProps() an asynchronous function in Next.js? Next.JS Redux 调度在 getStaticProps() 中不起作用 - Next.JS Redux dispatch not working in getStaticProps() 如何在 Next.js 中调试 getStaticProps(和 getStaticPaths) - How to debug getStaticProps (and getStaticPaths) in Next.js 来自 getStaticProps 与 Next.js 的无效响应 - Invalid response from getStaticProps with Next.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM