[英]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.