簡體   English   中英

Next.js,getStaticProps 不工作。 類型錯誤:無法讀取未定義的屬性(讀取“地圖”)

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

嘗試做這樣的事情:

  1. 將您的博客組件寫入文件 (Blog.tsx/jsx):

function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

export default Blog

  1. Go 到您將呈現此組件的頁面(例如它可以是 index.tsx/jsx)
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM