javascript - 无法读取未定义的属性“地图”(尝试从 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;
解决方案
then()
您需要从第一个回调中返回 JSON 。
.then((response) => {
if (response.ok) {
return response.json();
}
})
不这样做会导致jsonData
在下一个回调中未定义。
MDN 文档有一个关于在此处获取 JSON 的简单示例。他们使用隐式返回来获得更短的语法,但他们正在返回.json()
调用的结果。
推荐阅读
- join - 当我在连接查询中使用“with”时,选择除了 laravel eloquent 中的某些列
- d3.js - 使用 D3.js 将 Fontastic 图标附加到 SVG
- python-3.x - python列表中的数据
- jasmine - 测试用例单独运行时通过,但在组中运行时失败
- java - s3 select:如何获取镶木地板文件的列名?
- php - PHP:如何将新转换的ffmpeg文件保存到临时文件中
- python-3.x - 类型错误:更新()缺少 1 个必需的位置参数:“文档”
- amazon-s3 - 尽管获得了完全许可,但 aws iam 用户访问被拒绝
- r - 有没有办法用 R 中的包 sarima 来模拟具有趋势的数据?
- react-native-android - 为什么我不能在 react-native 中更改按钮的颜色