javascript - 如何在 React 中的对象内显示对象数组?

标签 javascript arrays reactjs object

我正在尝试制作一个模拟新闻 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;

我目前得到的错误是 map 不是一个函数。

来自 API 的响应:

enter image description here

//已编辑:将文章从数组更改为对象。

//感谢大家...devserkan 的回答对我帮助最大,我现在可以继续我的项目了!

最佳答案

首先,如前所述,您应该将 articles 状态作为数组保存在您的状态中,因为它是您响应中的数组。然后你可以很容易地映射它。这是一个工作示例。我在这里伪造 API 响应,但您可以根据自己的情况使用它。

class App extends React.Component {
  state = {
    articles: [],
  }

  response = {
    status: "ok",
    totalResults: 20,
    articles: [
      { author: "foo", title: "bar" },
      { author: "fizz", title: "buzz" },
    ]
  }

  getArticles = () =>
    new Promise( resolve =>
      setTimeout( () => resolve(this.response)), 500)

  componentDidMount() {
    this.getArticles()
      .then(response => this.setState({articles: response.articles}))
  }

  render() {
    const {articles} = this.state;
    return (
      <div>
        {
          articles.map( article => (
            <div>
            <p>Author: {article.author}</p>
            <p>Title: {article.title}</p>
            </div>
          ))
        }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

对于您的情况,只需查看我的示例并将您的 articles 状态设置为空数组。然后在 componentDidMount 方法中使用 newsApi 调用。我在此处提供您的固定代码,但无法确定它是否有效,因为我无法对其进行测试。

class App extends Component {
  constructor() {
    super();
    this.state = { articles: [] };
  }

  getNews = () =>
    newsapi.v2
      .topHeadlines({
        category: "business",
        language: "en",
        country: "us"
      })
      .then(response => {
        this.setState({ articles: response.articles });
      });

  componentDidMount() {
    this.getNews();
  }

  render() {
    let articles = 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>
                {articles.map(article => (
                  <p>{article.author}</p>
                ))}
              </p>
              <br />
              <Divider />
            </Paper>
            <div style={{ textAlign: "center", paddingTop: "20px" }} />
          </div>
        </div>
      </div>
    );
  }
}

我改变了什么?

  • 更改您所在州的 articles 形状。
  • 创建一个获取新闻的函数:getNews。
  • 在这个函数中获取新闻并像这样设置文章:this.setState({ articles: response.articles })
  • 添加 componentDidMount 并调用创建的函数。
  • 在 render 方法中将 article 名称更改为 articles 因为这样更一致。同时将 map 中的 articles 更改为 article
  • 文章中没有name,所以我用author改了。

关于javascript - 如何在 React 中的对象内显示对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583412/

相关文章:

javascript - 图片加载麻烦

java - 替换存储在字符串数组中的换行符

javascript - 如何在 React 中将裁剪参数设置为原始图像?

reactjs - 为什么 useEffect 不能在 return 语句中访问我的状态变量?

reactjs - 数组没有在 useState Hook 中更新?

javascript - 从 React Native WebView 中注入(inject)的 JavaScript 接收消息

javascript - fabric.js 获取 IText 对象的 "edit"状态

javascript - Angular 用户界面选择不起作用

c++ - 如何在 C++ 中创建一个从文件读取到十六进制数组的函数?

java - 如何检查二维数组中的对角邻居并将当前值设置为等于邻居数量