簡體   English   中英

Strapi v4 api 報錯“posts.map is not a function” NextJs

[英]Strapi v4 api error "posts.map is not a function" NextJs

index.js 文件

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts.map((post) => (
          <div key={post.id}>
            <h2>{post.Title}</h2>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/api/posts");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

這是我看到的錯誤“TypeError: posts.map is not a function” 有什么想法嗎?

posts是一個 object——你想要調用map的帖子數組被分配給posts.data

export default function Home({ posts }) {
  const { data } = posts; // unpack `data` from `posts`

  // call `map()` on `data`
  return (
    <div>
      {data && data.length
        ? data.map((post) => (
            <div key={post.id}>
              <h2>{post.attributes.Title}</h2>
            </div>
          ))
        : "no posts"}
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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