首页 > 解决方案 > 无法读取未定义的属性“地图”(尝试从 API 获取)

问题描述

我对 ReactJS 和 API 获取东西还很陌生,而且我已经被这个错误困扰了很长时间,所以我想知道是否有人知道问题是什么:P

我正在尝试获取一个 json 文件,然后从中提取一些数据。该 API 是https://hytale.com/api/blog/post/published但他们没有启用 CORS,所以我正在尝试使用一个名为 allorigins 的 CORS 代理。谢谢!

代码:

import React from "react";
import BlogPost from "./BlogPost";

class BlogPosts extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    };
  }

  componentDidMount() {
    fetch(
      `https://api.allorigins.win/raw?url=https://hytale.com/api/blog/post/published`
    )
      .then((response) => {
        if (response.ok) {
          console.log(response);
          response.json();
          console.log("Blogposts fetched PHASE 1!");
        }
      })
      .then((jsonData) => {
        this.setState({ posts: jsonData });
        console.log(this.state.posts);
        console.log(jsonData);
        console.log("Blogposts fetched PHASE 2!");
      });
  }

  render() {
      return (
        <div className="bg-gray-100 py-5 px-8 rounded-xl w-auto my-8 shadow-lg">
          <div className="text-3xl font-semibold">
            Latest BlogPosts or Announcements
          </div>
          <span className="inline-block my-3 mr-2 bg-green-100 px-3 py-1 rounded-2xl text-green-700">
            <b className="text-green-800">0</b> new blogposts in the last month.
          </span>
          <br />
          <p className="font-semibold text-xl mb-5 text-gray-700">
            Check out the latest 5 blogposts here:
          </p>

          {this.state.posts === null ? (
            <span className="text-gray-400 font-semibold text-lg">
              Loading BlogPosts...
            </span>
          ) : (
            this.state.posts.map((post) => {
              return <BlogPost
                name={post.title}
                date={post.publishedAt}
                author={post.author}
                type={post.coverImage.contentType}
                image={
                  "https://cdn.hytale.com/variants/blog_thumb_" + post.coverImage.s3Key
                }
                text={post.bodyExcerpt}
                link="https://hytale.com/news/2020/12/december-2020-development-update"
              />
              })
          )}
        </div>
      );
  }
}

export default BlogPosts;

标签: javascriptreactjs

解决方案


then()您需要从第一个回调中返回 JSON 。

.then((response) => {
  if (response.ok) {
    return response.json();
  }
})

不这样做会导致jsonData在下一个回调中未定义。

MDN 文档有一个关于在此处获取 JSON 的简单示例。他们使用隐式返回来获得更短的语法,但他们正在返回.json()调用的结果。


推荐阅读