【问题标题】:JSON format leads to .map is not a functionJSON 格式导致 .map 不是函数
【发布时间】:2022-02-14 03:28:58
【问题描述】:

使用当前的 Strapi 输出 JSON 的方式,我总是得到错误 .map is not a function。它是一个 NEXT.JS 前端。会不会是因为 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":"\nFACTS\nOS:\nSetting:\nSci-Fi\nGenre:\nRPG\nRelease Year:\n2014\nPayment Model:\nfree to play\nPVP:\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}}}

【问题讨论】:

  • 如果您的构建工具处理optional chaining,您可以简化此操作,只需执行posts?.data?.map?.(...) ?? null

标签: reactjs next.js strapi


【解决方案1】:

这是因为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>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2015-10-18
    • 2021-12-03
    • 2020-08-13
    相关资源
    最近更新 更多