首页 > 解决方案 > 如何在 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 的回答帮助最大,我现在可以继续我的项目了!

标签: javascriptarraysreactjsobject

解决方案


您将文章设置为对象而不是数组。然后,当您尝试“映射”您的文章时,您会收到一个错误,因为对象没有映射功能。

您可以通过将您所在州的文章对象设置为数组来解决此问题:

this.setState({ articles: response.articles }); 

注意我删除了响应周围的花括号以防止创建新对象


推荐阅读