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