[英]TypeError: Cannot read properties of undefined (reading 'call') on Next.js
[英]Next.js, getStaticProps not working. TypeError: Cannot read properties of undefined (reading 'map')
我创建了一个从 create-next-app 开始的项目。 在Blog.js页面内,我尝试使用getStaticProps()
function 从https://jsonplaceholder.typicode.com/posts获取。
我使用了指南https://nextjs.org/docs/basic-features/data-fetching/get-static-props#using-getstaticprops-to-fetch-data-from-a-cms 。 一切都完成后,我在浏览器中打开页面,它告诉我
Server Error
TypeError: Cannot read properties of undefined (reading 'map')
这是代码
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Blog
您在要渲染的组件内部写入 function。 您要做的唯一情况是当您基于某些参数制作动态 URL 时,在这种情况下,您将混合使用 getStaticProps 和 getStaticPages。
尝试做这样的事情:
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
export default Blog
import type { NextPage } from "next";
import Blog from 'wherever it is'
const Home: NextPage = ({posts}) => {
return (
<>
<Blog posts={posts}/>
</>
);
};
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Home;
Ps.: 当你使用 map 时,不要忘记 key 属性;) 希望它能帮助你,来自巴西的拥抱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.