javascript - 如何在 React 中的对象内显示对象数组?
问题描述
我正在尝试制作一个模拟新闻反应应用程序,并且我正在使用 newsapi 的节点包。这将返回一个响应,该响应在一个对象中包含一组对象。我将状态设置为 newsapi 函数的响应,当我将它记录到控制台时,我得到了对象。我只是无法在我的网站上显示它,因为我不知道如何在数组中显示对象的状态。
这是我的 App.js:
import React, { Component } from "react";
import Paper from "@material-ui/core/Paper";
import Divider from "@material-ui/core/Divider";
const NewsAPI = require("newsapi");
const newsapi = new NewsAPI("APIKEY");
class App extends Component {
constructor() {
super();
this.state = { articles: {} };
newsapi.v2
.topHeadlines({
category: "business",
language: "en",
country: "us"
})
.then(response => {
this.setState({ articles: { response } });
console.log(this.state.articles.response.articles[2]);
});
}
render() {
let article = this.state.articles;
return (
<div>
<div style={{ display: "flex" }}>
<div
style={{ marginLeft: "23em", width: "75%", paddingBottom: "20px" }}
>
<Paper>
<div style={{ textAlign: "center" }}>
<p style={{ margin: "50px" }}>
<b />
</p>
<br />
</div>
<p>
{article.map(articles => (
<p>{articles.name}</p>
))}
</p>
<br />
<Divider />
</Paper>
<div style={{ textAlign: "center", paddingTop: "20px" }} />
</div>
</div>
</div>
);
}
}
export default App;
我目前收到地图不是函数的错误。
来自 API 的响应:
// 已编辑:将文章从数组更改为对象。
// 感谢大家... devserkan 的回答帮助最大,我现在可以继续我的项目了!
解决方案
您将文章设置为对象而不是数组。然后,当您尝试“映射”您的文章时,您会收到一个错误,因为对象没有映射功能。
您可以通过将您所在州的文章对象设置为数组来解决此问题:
this.setState({ articles: response.articles });
注意我删除了响应周围的花括号以防止创建新对象
推荐阅读
- php - 如何将多张图片保存到 Laravel 的数据库中?
- scala - 如何在 Spark SQL DSL 中表示数学表达式
- javascript - 在 .map 中添加条件
- schema.org - 第二页和连续页的类别页面json-ld模式?
- r - R条形图:xlim中不允许NA
- cakephp - Cake3:如何与不同数据库中的表建立belongsToMany关联?
- javascript - 鼠标停止时继续滚动容器
- regex - 如何让 sed 替换第一次出现的以多字符分隔符结尾的复杂字符串?
- python - 在日志记录中使用自 UNIX 纪元以来的秒数作为日期格式
- css - 设计带边框的倒角/挖角矩形