JSON格式导致.map不是函数



按照目前strapi输出JSON的方式,我总是会得到错误。map不是一个函数。它是NEXT.JS Frontent。这可能是因为JSON没有作为数组输出吗?

import React, { useEffect } from "react";
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() {
// get games from the api
const res = await fetch("http://localhost:1337/api/games");
const posts = await res.json();
return {
props: { posts },
};
}

我得到了:TypeError:posts.map不是一个函数

有人给JS初学者一个如何解决这个问题的建议吗?

JSON输出如下:

{"data":[{"id":1,"attributes":{"title":"Guild Wars 2","createdAt":"2022-02-04T20:14:17.254Z","updatedAt":"2022-02-05T10:52:55.696Z","publishedAt":"2022-02-05T10:52:55.693Z","url":"https://www.guildwars2.com","description":"Guild Wars 2 is an online role-playing game with fast-paced action combat, a rich and detailed universe of stories, awe-inspiring landscapes to explore, two challenging player vs. player modes—and no subscription fees!","free":false,"feature_combat":"Fast-paced combat and choose from an arsenal of professions, weapons, and playstyles. Attack on the move, dodge and roll away from enemy blows, and come to your allies' rescue midbattle.","feature_world":"A beautifull designed, rich and detailed universe of stories, awe-inspiring landscapes to explore.","feature_quests":"No questgivers but an exploartion oriented roam around quest system with housands of stories that change based on the actions of players like you.","feature_grouping":"In the open world, you can team up with every player you meet—no grouping required! Also offeres Raids and dungeons for groups.","feature_usp":"Quick, furious matches between small groups of players in organized PvP or join hundreds of other players in the grand battles of World vs. World"}},{"id":2,"attributes":{"title":"Firefly Online","createdAt":"2022-02-05T11:01:39.549Z","updatedAt":"2022-02-05T11:04:40.562Z","publishedAt":"2022-02-05T11:04:40.558Z","url":"www.keepflying.com","description":"nFACTSnOS:nSetting:nSci-FinGenre:nRPGnRelease Year:n2014nPayment Model:nfree to playnPVP:nPay for features:nItem Shop:nMonthly fee:nLanguage: ","free":null,"feature_combat":"Seek out adventures","feature_world":"Assume the role of a ship captain – create a crew and customize a ship","feature_quests":"Online role playing game based on Firefly, Joss Whedon’s cult-hit television series Firefly","feature_grouping":"Hire a crew","feature_usp":"Cross-platform player experience across devices"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}

这是因为posts是一个JSON对象,而不是可以使用map()函数的数组。相反,您需要先将数组赋予map()函数,然后才能提取标题。

要访问JSON对象的数组,可以使用posts['data']

export default function Home({ posts }) {
return (
<div>
{posts &&
posts["data"].map((post) => (
<div key={post.id}>
<h2>{post.attributes.title}</h2>
</div>
))}
</div>
);
}

最新更新